Creating a Promise
Most of the time you consume promises other people made, and knowing how to make one is what lets you wrap anything that is not already a promise.
The Promise constructor takes an executor receiving resolve and reject, and runs it immediately. Promise.resolve and Promise.reject make already-settled ones. The main real use is wrapping an older callback-based .
EXERCISE
1The Constructor and Its Executor
You hand the constructor a function, it hands that function two ways to finish, and it runs it straight away.
The shape:
const p = new Promise((resolve, reject) => {
const ok = true;
if (ok) {
resolve("it worked");
} else {
reject(new Error("it did not"));
}
});
p.then((value) => {
console.log(value); // it worked
});
The function you pass in is called the executor. It receives two functions, conventionally named resolve and reject, and calling either one settles the promise.
The executor runs immediately and synchronously:
console.log("A");
const p = new Promise((resolve) => {
console.log("B"); // runs right now, on the stack
setTimeout(() => resolve("C"), 0);
});
console.log("D");
p.then(console.log);
// A
// B
// D
// C
B printed before D. Creating a promise does not defer anything on its own; the executor body is ordinary synchronous code. Only the settling is deferred, and only because a timer was used here.
That surprises people who read new Promise as "start something in the background". It does not. Whatever is inside runs now.
Always reject with an Error, not a string:
// Poor: loses the stack trace
reject("something went wrong");
// Good: carries a stack trace and works with instanceof
reject(new Error("something went wrong"));
Unit 9 covers error types properly. The short reason is that an Error records where it came from and a string does not, so a rejected string produces a failure you cannot locate.
And a throw inside the executor becomes a rejection:
const p = new Promise(() => {
throw new Error("boom");
});
p.catch((err) => {
console.log(err.message); // boom
});
That is a genuine convenience: you do not have to wrap the executor in a try block, because the constructor does it for you.
Pro Tip: If you find yourself writing
new Promisearound something that already returns a promise, stop. That is the promise constructor antipattern, and the wrapper adds a layer that can only lose errors.new Promiseis for bridging something that is not promise-based into something that is, and the next exercise is what that looks like.
EXERCISE
2Wrapping a Callback API
The constructor's real job is turning an older interface into one you can await.
Plenty of APIs predate promises and still take a callback. Wrapping one is the standard use of new Promise, and the pattern is always the same.
A timer, wrapped:
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function run() {
console.log("start");
await delay(1000);
console.log("one second later");
}
setTimeout has no idea what a promise is. Three lines turn it into something await understands, and delay is a genuinely useful helper you will write in most projects.
A Node-style callback, wrapped:
// Node convention: callback(error, result)
function readFilePromise(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, "utf8", (error, data) => {
if (error) {
reject(error);
} else {
resolve(data);
}
});
});
}
Error first goes to reject, result goes to resolve. ships util.promisify which does exactly this for any function following that convention, so you rarely write it by hand. Writing it once is what makes promisify obvious.
An event-based API, wrapped:
function loadImage(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(new Error(`failed to load ${src}`));
img.src = src;
});
}
const img = await loadImage("/logo.png");
Note the ordering: the handlers are attached before src is set, because setting src is what starts the load. Getting that backwards is a real bug, and it is the kind of detail wrapping forces you to think about once instead of at every call site.
Two already-settled shortcuts:
Promise.resolve(42); // fulfilled immediately
Promise.reject(new Error("nope")); // rejected immediately
// Useful for a cache that should look async either way:
function getUser(id) {
if (cache.has(id)) {
return Promise.resolve(cache.get(id));
}
return fetch(`/api/users/${id}`);
}
The caller writes await getUser(1) and never has to know whether it was cached. Returning the raw value instead would make the function sometimes-async, which is exactly the inconsistency promises exist to remove.
Pro Tip: A wrapper should be the thinnest possible layer: attach the handlers, call
resolveorreject, do nothing else. Any logic you add inside the executor runs outside the promise chain's error handling, so a mistake there produces an unhandled rejection rather than something your.catchcan see.
EXERCISE
3Promises Are Eager, Not Lazy
Creating a promise starts the work immediately, which matters as soon as you want to delay or repeat it.
A promise represents work that has already started. This follows from the executor running synchronously, and it catches people out in three specific situations.
Creating is starting:
const p = fetch("/api/user"); // the request is already in flight
// ...five seconds of other code...
const user = await p; // await does not start it, it joins it
await is not what triggers the request. It only waits for something already running.
Which is why this is slower than it looks:
// Sequential: 900ms, because each fetch starts only after the last finishes
const a = await fetch("/api/a");
const b = await fetch("/api/b");
const c = await fetch("/api/c");
// Concurrent: 300ms, because all three started before any await
const pa = fetch("/api/a");
const pb = fetch("/api/b");
const pc = fetch("/api/c");
const [ra, rb, rc] = [await pa, await pb, await pc];
Same three requests, same awaits, three times faster. The only change is when each promise was created.
And why a promise cannot be retried:
const p = fetch("/api/user");
try {
await p;
} catch {
await p; // does NOT retry: same settled promise, same rejection
}
The promise already settled. Awaiting it again returns the same outcome instantly. To retry you need to call the function again, which means what you want to hold is the function, not the promise:
async function retry(makePromise, attempts = 3) {
for (let i = 0; i < attempts; i++) {
try {
return await makePromise(); // a fresh promise each attempt
} catch (err) {
if (i === attempts - 1) throw err;
}
}
}
const user = await retry(() => fetch("/api/user"));
Passing () => fetch(...) rather than fetch(...) is the whole difference. The arrow defers creation until the moment it is called, which is laziness added by hand.
The same reasoning explains a common surprise with rejections:
const p = Promise.reject(new Error("boom"));
// Unhandled rejection warning fires here, at the end of this turn
setTimeout(() => {
p.catch(() => console.log("handled")); // too late for the warning
}, 0);
The runtime checks for handlers once the microtask queue drains. Attaching one in a later macrotask still works, but the warning has already been reported.
Pro Tip: When you need work that can be delayed, repeated or cancelled, store a function that creates the promise rather than the promise itself. A promise is a running operation; a function that returns one is a recipe. Retry, backoff, lazy loading and request deduplication all depend on holding the recipe.
