JavaScript Promises: from the executor to async and await
A promise is a value that stands for a result which is not here yet. It is how JavaScript names one operation that finishes later: a timer, a file read, a request to a server. The work starts, the promise comes back at once, and the result arrives in a callback that runs when the work is done. This article builds the whole model from the constructor up: the three states, the chain, the four combinators, async and await, and the order in which the callbacks run.
Every program below is a file of its own, run with Node.js on Linux, and the block under each one is the real output of that run. The chains built by hand here are the same ones the JavaScript course takes apart in its promises lesson and the lessons that follow it.
Why promises
Before promises, an asynchronous result was delivered to a callback: a function the caller passed in, which the work called when it was done. One step is fine. Two steps mean a callback inside a callback, each with its own error argument, and the code that belongs together drifts to the right of the screen. The program below loads a user and then the orders of that user.
The file callbacks.mjs:
function loadUser(id, callback) {
setTimeout(() => callback(null, { id, name: 'Ada' }), 10);
}
function loadOrders(user, callback) {
setTimeout(() => callback(null, [{ id: 1, total: 42 }]), 10);
}
loadUser(7, (error, user) => {
if (error) {
console.log('user:', error.message);
return;
}
loadOrders(user, (ordersError, orders) => {
if (ordersError) {
console.log('orders:', ordersError.message);
return;
}
console.log('the callback style:', user.name, orders.length, 'order(s)');
});
});
node callbacks.mjs
the callback style: Ada 1 order(s)
Every step repeats the same if (error) check, and nothing catches a failure of the whole sequence in one place. A promise flattens this: the work returns an object, the next step is attached to that object, and one handler at the end sees every failure. The functions stop taking callbacks and start returning a value that says "later".
The three states
A promise is in exactly one of three states at any moment: pending while the work runs, fulfilled with a value, or rejected with a reason. Pending is the only state it can leave, and it leaves it once: after that the promise is settled and never changes again. There is no public property that reports the state, but util.inspect shows it, and every handler behaves accordingly.
The file states.mjs:
import { inspect } from 'node:util';
const pending = new Promise(() => {});
const fulfilled = Promise.resolve('a value');
const rejected = Promise.reject('a reason');
void rejected.catch(() => {});
console.log('pending: ', inspect(pending));
console.log('fulfilled:', inspect(fulfilled));
console.log('rejected: ', inspect(rejected));
node states.mjs
pending: Promise { <pending> }
fulfilled: Promise { 'a value' }
rejected: Promise { <rejected> 'a reason' }
The first promise never settles, because its executor never calls anything; the other two were settled before the program looked at them. A second call to resolve or reject is ignored, and so is a throw after a settlement: once the state is decided, the value and the reason are fixed.
Creating a promise
new Promise(executor) takes one function and calls it at once, before the constructor returns. The executor receives two functions, resolve for the value and reject for the reason, and a throw inside it rejects the promise instead of escaping to the caller. That is the whole constructor: there is no start method, and a promise does not run anything by itself.
The file executor.mjs:
const promise = new Promise((resolve) => {
console.log('the executor runs at once');
resolve('the value');
});
console.log('the constructor has already returned');
const handlers = [
promise.then((value) => console.log('the then callback is a microtask:', value)),
new Promise((resolve, reject) => {
reject(new Error('the work failed'));
}).catch((error) => console.log('reject hands over the reason:', error.message)),
new Promise(() => {
throw new Error('a throw in the executor');
}).catch((error) => console.log('a throw rejects the promise too:', error.message)),
];
await Promise.all(handlers);
node executor.mjs
the executor runs at once
the constructor has already returned
the then callback is a microtask: the value
reject hands over the reason: the work failed
a throw rejects the promise too: a throw in the executor
The executor line printed before the line after the constructor, so the work had already started when the promise was returned. The callbacks of then and catch waited for the microtask queue, which is the one rule that explains every order in the rest of the article. A rejection reaches catch with the reason, whether it came from a reject call or from a throw.
then, catch and finally
then(onFulfilled, onRejected) registers the callback for a value and returns a new promise. catch(onRejected) is the same thing with the first argument left out, and it is where a rejection normally goes. finally(onFinally) takes a callback with no arguments, runs it on both paths, and passes the value or the rejection on unchanged: it is for cleanup, not for reading the result.
The file finally.mjs:
function load(ok) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (ok) {
resolve('the contents');
} else {
reject(new Error('the load failed'));
}
}, 10);
});
}
await load(true)
.finally(() => console.log('cleanup after a success'))
.then((value) => console.log('the value:', value));
await load(false)
.finally(() => console.log('cleanup after a failure'))
.catch((error) => console.log('the error:', error.message));
node finally.mjs
cleanup after a success
the value: the contents
cleanup after a failure
the error: the load failed
Both cleanups ran before the handlers that used the result, and the rejection still reached its catch. The callback of finally cannot change the value: what it returns is ignored, unless it throws or returns a rejected promise, which replaces the outcome.
Chaining
Chaining works because then returns a new promise, and what its callback returns decides the value of that promise. Three kinds of return matter: a plain value fulfils the next promise with it; a promise makes the next step wait for that promise and receive its value; a throw rejects the next promise. A chain is therefore a sequence of steps with one error path, not a set of nested callbacks.
The file chain.mjs:
function double(value) {
return new Promise((resolve) => {
setTimeout(() => resolve(value * 2), 10);
});
}
await double(1)
.then((value) => {
console.log('the first step:', value);
return value + 1;
})
.then((value) => {
console.log('the second step:', value);
return double(value);
})
.then((value) => {
console.log('the third step:', value);
throw new Error('the fourth step failed');
})
.catch((error) => {
console.log('the catch:', error.message);
return 'recovered';
})
.then((value) => console.log('after the catch:', value));
node chain.mjs
the first step: 2
the second step: 3
the third step: 6
the catch: the fourth step failed
after the catch: recovered
The first step doubled the one it was given, the second returned a plain number, and the third returned a promise, so the fourth step waited for it and received six. The throw ended that step, the catch took over, and the value it returned fulfilled the chain again: the last then ran with recovered. A catch in the middle is a recovery point, not the end of the chain.
Error propagation and the unhandled rejection
A rejection skips every then that has no rejection handler and stops at the first catch. If the chain ends without one, the promise is rejected and nobody listens. At the end of the microtask checkpoint Node.js emits an unhandledRejection event; the program below listens for it, which is how a process logs such a failure before it dies.
The file rejection-event.mjs:
process.on('unhandledRejection', (reason) => {
console.log('the process saw an unhandled rejection:', reason.message);
});
void Promise.reject(new Error('nobody listens'));
setTimeout(() => console.log('the program kept running'), 10);
node rejection-event.mjs
the process saw an unhandled rejection: nobody listens
the program kept running
A listener is a last resort for logging and for a clean shutdown, not a way to recover: the value is gone. Without a listener, the default since Node.js 15 is to report the reason and exit with a non-zero code. The program from before, with the listener removed, ends like this:
The file bare-rejection.mjs:
void Promise.reject(new Error('nobody listens'));
node bare-rejection.mjs > /dev/null 2>&1; echo "exit code: $?"
exit code: 1
The message on standard error names the reason and the file, and the exit code is 1, so a test runner or a container sees the failure. Give every chain a final catch, even when the only thing it can do is log the error and rethrow it.
Promise.all, allSettled, race and any
Four static methods run several promises together, and they differ in two questions: does one failure end the whole thing, and which value is the answer. Every one of them takes an array of promises or plain values, returns a single promise, and keeps the order of the calls in its result.
The file combinators.mjs:
const delay = (value, ms) =>
new Promise((resolve) => {
setTimeout(() => resolve(value), ms);
});
const values = await Promise.all([delay('a', 10), delay('b', 30), 'c']);
console.log('all:', values.join(','));
const results = await Promise.allSettled([
delay('the answer', 10),
Promise.reject(new Error('the second call failed')),
]);
console.log('allSettled:', results.map((result) => result.status).join(','));
console.log('the reason:', results[1].reason.message);
const winner = await Promise.race([delay('slow', 30), delay('fast', 10)]);
console.log('race:', winner);
const first = await Promise.any([Promise.reject(new Error('no')), delay('later value', 10)]);
console.log('any:', first);
try {
await Promise.any([Promise.reject(new Error('one')), Promise.reject(new Error('two'))]);
} catch (error) {
console.log('any rejects with:', error.name, error.errors.map((item) => item.message).join(','));
}
node combinators.mjs
all: a,b,c
allSettled: fulfilled,rejected
the reason: the second call failed
race: fast
any: later value
any rejects with: AggregateError one,two
all returned three values in the order of the calls, including the plain string that was not a promise at all. allSettled returned both outcomes as data, so a report can print the reason of a failed item without an exception. race took the first promise to settle, and any skipped the rejection and took the first value; when every promise rejects, any rejects with an AggregateError that holds all the reasons.
| Method | Fulfils when | Rejects when | The value | Use it for |
|---|---|---|---|---|
| Promise.all | every promise has fulfilled | the first one rejects | an array of values, in the order of the calls | steps that must all succeed, such as a page that needs three requests |
| Promise.allSettled | every promise has settled | never | an array of {status, value} or {status, reason} | a report over many items, where one failure is data |
| Promise.race | the first promise fulfils | the first promise rejects | the value or reason of the first to settle | a timeout, or a choice between mirrors |
| Promise.any | the first promise fulfils | every promise has rejected | the first value to arrive | redundant sources, where one working answer is enough |
all does not cancel the promises that lost. They keep running, their values are dropped, and a later rejection among them is not reported to the combined promise, which has already settled. The program below shows the early rejection and the work that goes on without it.
The file all-rejects.mjs:
const delay = (value, ms) =>
new Promise((resolve) => {
setTimeout(() => resolve(value), ms);
});
try {
await Promise.all([
delay('a', 10),
Promise.reject(new Error('the second call failed')),
delay('c', 30),
]);
} catch (error) {
console.log('all rejected at once:', error.message);
}
console.log('the other two calls were still running');
node all-rejects.mjs
all rejected at once: the second call failed
the other two calls were still running
The failure arrived without waiting for the thirty millisecond call, and the program went on while that call was still pending. If the other results matter even when one fails, use allSettled; if the work can be cancelled, pass it an AbortSignal, as the timeout section shows.
Promise.resolve, Promise.reject and Promise.withResolvers
Promise.resolve(value) returns a promise fulfilled with that value, and Promise.reject(reason) one rejected with the reason. The first one is how a function that sometimes has an answer already and sometimes has to wait keeps a single return type; it also adopts a thenable, a plain object with a then method. Promise.withResolvers, standard since ES2024, returns the promise together with its resolve and reject, for the cases where those have to leave the executor.
The file statics.mjs:
const value = await Promise.resolve('a plain value');
console.log('resolve:', value);
const array = await Promise.resolve([1, 2, 3]);
console.log('the unwrap is shallow:', Array.isArray(array), array.length);
try {
await Promise.reject(new Error('a reason'));
} catch (error) {
console.log('reject:', error.message);
}
const thenable = {
then(resolve) {
resolve('from a thenable');
},
};
console.log('a thenable is adopted:', await Promise.resolve(thenable));
const { promise, resolve } = Promise.withResolvers();
setTimeout(() => resolve('resolved from outside'), 10);
console.log('withResolvers:', await promise);
node statics.mjs
resolve: a plain value
the unwrap is shallow: true 3
reject: a reason
a thenable is adopted: from a thenable
withResolvers: resolved from outside
The array came back as one value, not as three: resolve fulfils with what it is given and does not unwrap arrays. The thenable was adopted, and its then method ran as part of the resolution. withResolvers gave the resolving function a name outside the constructor, which is what an event listener or a callback of another library needs.
Converting callbacks to promises
Node.js still has callback APIs, with the convention that the callback receives an error first and the value second. util.promisify turns such a function into one that returns a promise, and many modules now ship a promise version as well: node:fs/promises is node:fs with promises. When the API does not follow the convention, the wrapper is three lines and a new Promise.
The file promisify.mjs:
import { promisify } from 'node:util';
import { readFile } from 'node:fs';
const readFileAsync = promisify(readFile);
const text = await readFileAsync(new URL(import.meta.url), 'utf8');
console.log('the first line of this file:', text.split('\n')[0]);
function loadUser(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) {
resolve({ id, name: 'Ada' });
} else {
reject(new Error('no such user'));
}
}, 10);
});
}
const user = await loadUser(7);
console.log('the user:', user.name);
try {
await loadUser(0);
} catch (error) {
console.log('the failure:', error.message);
}
node promisify.mjs
the first line of this file: import { promisify } from 'node:util';
the user: Ada
the failure: no such user
The promisified readFile resolved with the text and rejected with the original error object, which still has code, errno and the rest. The hand-written wrapper did the same for a callback that is not error-first by accident: the new Promise is the adapter, and the callback only has to call resolve or reject. For a method that uses this, bind it before promisifying it.
async and await: the same chain, written straight down
An async function always returns a promise, and await pauses that function until the promise settles, then gives back its value or throws its reason. Nothing else pauses: the rest of the program runs while the function waits. That is exactly a chain, with the steps in reading order and try/catch in place of catch. The program below is the chain from the previous section, rewritten.
The file async-await.mjs:
function double(value) {
return new Promise((resolve) => {
setTimeout(() => resolve(value * 2), 10);
});
}
async function run() {
try {
const first = await double(1);
console.log('the first step:', first);
const second = first + 1;
console.log('the second step:', second);
const third = await double(second);
console.log('the third step:', third);
throw new Error('the fourth step failed');
} catch (error) {
console.log('the catch:', error.message);
return 'recovered';
}
}
console.log('after the call:', await run());
async function answer() {
return 42;
}
console.log('an async function returns a promise:', answer() instanceof Promise);
console.log('await unwraps it:', await answer());
node async-await.mjs
the first step: 2
the second step: 3
the third step: 6
the catch: the fourth step failed
after the call: recovered
an async function returns a promise: true
await unwraps it: 42
The output is the same sequence of values, and the throw became an exception that the try caught, so the function could return a normal value again. The last two lines show the other half of the rule: a function declared async returns a promise even when it returns a number, and await on that promise gives the number back. await on a plain value is allowed and costs one microtask.
Sequential and parallel work
await inside a loop runs the steps one after another: each one starts when the previous has finished. That is right when a step needs the result of the one before, and wrong when the steps are independent, because the total time is the sum of all of them. Starting every promise first and awaiting them together takes as long as the slowest one.
The file sequence.mjs:
import { setTimeout as sleep } from 'node:timers/promises';
async function work(name) {
console.log('start', name);
await sleep(20);
console.log('finish', name);
}
console.log('one by one:');
await work('a');
await work('b');
console.log('all at once:');
await Promise.all([work('a'), work('b')]);
node sequence.mjs
one by one:
start a
finish a
start b
finish b
all at once:
start a
start b
finish a
finish b
One by one, the second start waited for the first finish. All at once, both started before either finished, and the results were collected in the order of the calls. The same rule holds in a loop: for (const id of ids) await load(id) is sequential, and await Promise.all(ids.map((id) => load(id))) is parallel. Parallel work needs a limit when the list is long: a thousand requests at once will hit the server's rate limit long before they hit the machine's.
Timeouts with AbortSignal and race
A promise cannot be cancelled, but the operation behind it can be told to stop through an AbortSignal. AbortSignal.timeout(ms) returns a signal that aborts itself after that many milliseconds, and APIs that accept a signal reject with an AbortError when it fires. fetch, the file system and the promise timers of node:timers/promises all take one.
The file timeout.mjs:
import { setTimeout as sleep } from 'node:timers/promises';
try {
await sleep(1000, 'too late', { signal: AbortSignal.timeout(20) });
} catch (error) {
console.log('the sleep was aborted:', error.name);
}
const slow = sleep(1000, 'the slow answer');
const timeout = sleep(20).then(() => {
throw new Error('the call took too long');
});
try {
await Promise.race([slow, timeout]);
} catch (error) {
console.log('the race timed out:', error.message);
}
node timeout.mjs
the sleep was aborted: AbortError
the race timed out: the call took too long
The first sleep rejected with an AbortError and stopped waiting. The second part raced the call against a timer and lost on purpose: the race gives a timeout to any promise, including one that knows nothing about signals, but it does not cancel the loser. The request keeps running until it finishes or the process exits, so prefer a real signal where the API has one.
Microtask order versus setTimeout
JavaScript runs one thing at a time on a call stack. Asynchronous work is queued in two places: the microtask queue, which holds promise callbacks, queueMicrotask callbacks and the continuations after await, and the macrotask queue, which holds timers, I/O and events. After every macrotask the engine drains the whole microtask queue before the next macrotask; new microtasks added while draining run in the same drain.
The file order.mjs:
console.log('1 script start');
setTimeout(() => console.log('2 setTimeout'), 0);
void Promise.resolve().then(() => console.log('3 promise then'));
queueMicrotask(() => console.log('4 queueMicrotask'));
void (async () => {
console.log('5 async function start');
await null;
console.log('6 after await');
})();
console.log('7 script end');
node order.mjs
1 script start
5 async function start
7 script end
3 promise then
4 queueMicrotask
6 after await
2 setTimeout
The script ran to the end first, printing 1, 5 and 7: the async function started synchronously and stopped at its await. Then the microtask queue was drained in the order the callbacks were queued: the then of the already fulfilled promise (3), the explicit queueMicrotask (4), and the continuation of the async function (6). Only after the queue was empty did the timer run (2). If the puzzle is new, the event loop lesson and the timers lesson build it up from the stack.
Common mistakes
The forgotten return
A then callback that does not return anything fulfils the next promise with undefined, even when it worked on the value. The next step then reads undefined, and the failure is silent because nothing threw.
The file forgotten-return.mjs:
await Promise.resolve('a value')
.then((value) => {
value.toUpperCase();
})
.then((value) => {
console.log('the next step got:', value);
});
node forgotten-return.mjs
the next step got: undefined
The fix is one word: return value.toUpperCase();. The same mistake hides a returned promise: without the return the next step does not wait for it.
Nested then instead of a chain
A then inside a then starts a second chain that the outer one knows nothing about. The outer chain moves on with undefined, and an error inside the nested work never reaches the outer catch.
The file nested-then.mjs:
const slow = (value) =>
new Promise((resolve) => {
setTimeout(() => resolve(value), 20);
});
void Promise.resolve(1)
.then((value) => {
void slow(value + 1).then((inner) => {
console.log('the nested chain finished:', inner);
});
})
.then((value) => {
console.log('the outer chain moved on with:', value);
});
await slow(0);
await Promise.resolve(1)
.then((value) => slow(value + 1))
.then((inner) => {
console.log('the returned promise is waited for:', inner);
});
await slow(0);
node nested-then.mjs
the outer chain moved on with: undefined
the nested chain finished: 2
the returned promise is waited for: 2
The outer chain printed undefined before the nested work had finished, and a rejection inside the nested work would have gone to the process instead of the outer handler. Returning the inner promise joins the two chains: the last line shows the outer chain waiting for the value.
await in a loop
await inside a for loop is correct when one step needs the previous result and wrong when the steps are independent. The program counts how many calls are in flight at the same time.
The file loop.mjs:
import { setTimeout as sleep } from 'node:timers/promises';
let inFlight = 0;
let mostAtOnce = 0;
const work = async () => {
inFlight += 1;
mostAtOnce = Math.max(mostAtOnce, inFlight);
await sleep(20);
inFlight -= 1;
};
for (let i = 0; i < 3; i += 1) {
await work();
}
console.log('one at a time, at most in flight:', mostAtOnce);
mostAtOnce = 0;
await Promise.all([work(), work(), work()]);
console.log('all at once, at most in flight:', mostAtOnce);
node loop.mjs
one at a time, at most in flight: 1
all at once, at most in flight: 3
One at a time, the counter never went above one: every call waited for the previous one, and the total time is the sum. The fix is to start the calls first and await them together, which keeps the order of the results and runs them at the same time.
Swallowed errors
A catch that prints a fixed sentence throws the reason away. The log says that something failed and not what, and the caller cannot retry or report it.
The file swallowed.mjs:
await Promise.reject(new Error('the real problem')).catch(() => {
console.log('something went wrong');
});
await Promise.reject(new Error('the real problem')).catch((error) => {
console.log('the real problem:', error.message);
});
node swallowed.mjs
something went wrong
the real problem: the real problem
The second version keeps the message; a production handler also keeps the stack, logs the operation and either rethrows the error or returns a value that makes sense for the caller. Silence is worse than a crash: a crash at least says where it happened.
Where to go next
The promises lesson of the course takes the chain apart again with exercises and questions, the next lesson runs the combinators, and the one after it writes them with async and await. Errors in asynchronous code have their own lesson, errors in asynchronous code, and the AbortController lesson goes further than the timeout here. To test a promise, the node:test lesson shows the built-in runner, and Mocha is the framework with the longest history.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.15.0 (flat config, the recommended rules and no-floating-promises) on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev