A Promise represents a value that will be ready later. It is pending, then fulfilled (success) or rejected (error).
async / await
- Mark a function
asyncand it always returns a Promise - Inside it,
await promisepauses that function (not the whole server) until the result is ready - Handle errors with
try / catch
Running tasks in parallel
Awaiting one by one is slow when tasks don't depend on each other:
Promise.all([...])— run together, fail if any failsPromise.allSettled([...])— wait for all and report each resultPromise.race([...])/Promise.any([...])— the first to finish / succeed
Creating a promise
new Promise((resolve, reject) => { ... }) — useful for wrapping old APIs. For delays, node:timers/promises has setTimeout that returns a promise.
Top-level await
In ES modules you can use await directly at the top of a file.
Example
Example — Sequential vs parallel
JavaScript
import { setTimeout as wait } from 'node:timers/promises';
async function fetchUser(id) {
await wait(500); // pretend this is a database call
if (id === 0) throw new Error('User not found');
return { id, name: `User ${id}` };
}
console.time('sequential');
const a = await fetchUser(1);
const b = await fetchUser(2);
console.timeEnd('sequential'); // ~1000 ms
console.time('parallel');
const [c, d] = await Promise.all([fetchUser(3), fetchUser(4)]);
console.timeEnd('parallel'); // ~500 ms
const results = await Promise.allSettled([fetchUser(5), fetchUser(0)]);
results.forEach((r) => console.log(r.status, r.value?.name ?? r.reason.message));
// fulfilled User 5
// rejected User not found
try {
await fetchUser(0);
} catch (err) {
console.error('Caught:', err.message);
}
The parallel version takes about half the time. allSettled reports each result even when one fails, and try/catch handles the error from fetchUser(0).