First, a correction interviewers want to hear: you can't run promises in sequence, because a promise is work that has already started. You run functions that return promises, starting each one after the previous settles. With async/await that's a for...of loop with await inside; without it, it's a reduce that chains .then calls starting from Promise.resolve(). Collect results by order, stop on the first failure (or record every outcome, like allSettled, if the caller wants that), and for production add retries with backoff and an AbortSignal.
How can you execute an array of promises in sequence?
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
await inside for...of pauses the loop until each task settles, so the next one starts only then. A rejection throws out of the loop, which rejects the whole function and stops the remaining tasks. This is the opposite of Promise.all, which waits for work that is already running in parallel.
// Tasks are functions that return promises: a promise has already started, so only a// function lets us decide when each one begins.async function runInSequence(tasks) {const results = [];for (const task of tasks) results.push(await task()); // each starts after the previous endsreturn results;}
passes 3 checks run on every build, against the native method where there is one
- runs one after another and keeps order
- stops at the first failure
- an empty list resolves to []
Before async/await, sequencing was a reduce that builds one long chain: start with Promise.resolve([]), and each link calls the next task inside .then, so it can't start early. Promise.resolve(task()) lets tasks return plain values. A waterfall passes each result to the next task, which is the same reduce with the value itself as the accumulator.
// The same with reduce and no async/await: each link starts the next task when the previous settles.function runInSequence(tasks) {return tasks.reduce((chain, task) => chain.then((results) => Promise.resolve(task()).then((value) => [...results, value])),Promise.resolve([]),);}// A waterfall: each task receives the previous task's result.function waterfall(tasks, initial) {return tasks.reduce((chain, task) => chain.then(task), Promise.resolve(initial));}
passes 4 checks run on every build, against the native method where there is one
- reduce chain: same order and timing
- plain values from tasks are fine
- waterfall passes each result on
- a failure skips the rest
For a queue of independent jobs (uploading files, replaying offline edits), one failure shouldn't stop the rest: record { status, value | reason } per task, like allSettled but in order. Transient failures get retried with exponential backoff (100 ms, 200 ms, 400 ms…). An AbortSignal is checked between tasks (throwIfAborted rejects with the signal's reason) and passed to each task so a fetch inside can stop too. A progress callback drives a progress bar.
// In order, never rejecting: every task runs and reports its own outcome, with retries and an// optional AbortSignal that stops the queue between tasks.async function runAllInSequence(tasks, { retries = 0, delay = (attempt) => 100 * 2 ** attempt, signal, onProgress } = {}) {const results = [];for (let i = 0; i < tasks.length; i++) {signal?.throwIfAborted(); // rejects with signal.reasonlet attempt = 0;for (;;) {try {results.push({ status: 'fulfilled', value: await tasks[i]({ signal }) });break;} catch (reason) {if (attempt >= retries || signal?.aborted) {results.push({ status: 'rejected', reason });break;}await new Promise((resolve) => setTimeout(resolve, delay(attempt))); // back off, then try againattempt++;}}onProgress?.(i + 1, tasks.length);}return results;}
passes 5 checks run on every build, against the native method where there is one
- every task runs; outcomes are reported, not thrown
- retries with backoff, then succeeds
- gives up after the last retry
- abort stops the queue between tasks
- reports progress
Order-dependent writes
Database migrations, or edits a user made offline, must be applied in order: each depends on the one before. A parallel Promise.all would race them.
The accidental waterfall
The opposite mistake is common in agent-written code: awaiting independent requests one by one in a loop, which makes a page load take the sum of the requests instead of the longest. Sequence only what depends on order.
Upload queues
Upload widgets send files one at a time (or a few at a time), retry failures, show progress, and cancel when the user leaves: the advanced stage is that queue.
Passing an array of promises: they all started when they were created, so nothing is sequential.
tasks.forEach(async (t) => await t()):forEachdoesn't wait, so they run in parallel and the function returns at once.Starting the next task in the
reducecallback itself instead of inside.then.Retrying immediately in a tight loop instead of backing off, which hammers a server that's already struggling.
Sequencing independent requests that could run in parallel.
How would you run them in sequence with a timeout per task?
Race each task against a timer: await Promise.race([task(), new Promise((_, rej) => setTimeout(() => rej(new Error('timeout')), ms))]), or pass AbortSignal.timeout(ms) to tasks that accept a signal so the work actually stops.
What about something in between: at most N at a time?
That's a concurrency pool: start N tasks and start the next whenever one finishes (see the Promise.all answer's advanced stage).
How does for await...of relate?
for await (const x of source) awaits each value of an async iterable (or an iterable of promises) in turn. Over an array of already-created promises it waits in order, but the work still ran in parallel.
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
- developer.mozilla.org/en-US/docs/Web/API/AbortSignal/throwIfAborted
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of