Run Promises in sequence
Start each task after the previous one finishes and collect the results in order.
async function runInSequence(tasks) {
const results = [];
for (const task of tasks) results.push(await task());
return results;
}
Usage
const log = [];
const step = (name, ms) => () => new Promise(resolve => setTimeout(() => { log.push(name); resolve(name); }, ms));
await runInSequence([step('slow', 30), step('fast', 10)]); // → ['slow', 'fast']
log; // → ['slow', 'fast']
// Promises, unlike tasks, are already running:
log.length = 0;
await Promise.all([step('slow', 30)(), step('fast', 10)()]); // → ['slow', 'fast']
log; // → ['fast', 'slow']
Know the limits
- Pass functions that start the work, not promises: a promise is already running once it exists. The original took promises, so it ordered the results but not the work, as the last lines show.
- Use it when each step must finish before the next starts, such as sending one batch at a time under a rate limit. On a 429, wait for Retry-After (see Read a Retry-After header) before the next task.
- The first rejection stops the sequence; catch inside each task to keep going.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Run Promises in sequence from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Takes functions that start each task; the original took promises, which were already running concurrently. Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Convert Celsius to Fahrenheit — Apply the temperature conversion without rounding the result.
- Convert hex to RGB — Expand #rgb if needed and read the red, green and blue channels.
- Convert URL parameters to object — Read a query string into an object; repeated keys become arrays.