Run async tasks one after another
Promise.all starts everything at once, which is usually what you want and occasionally a disaster — think four PUT requests to the same record, or an endpoint that returns 429 the moment you exceed one call at a time.
Implement runSequentially(tasks), where tasks is an array of zero-argument functions that each return a promise. Call the first task, wait for it to settle, then call the next, and so on. Resolve with an array of the results in the same order as tasks. An empty array resolves with an empty array. If a task rejects, reject immediately with that same reason and do not call any of the remaining tasks.
Arguments
tasksArray<() => Promise>- Zero-argument functions, each returning a promise.
Returns
Promise<Array> — A promise that resolves with the results in task order. Rejects with the first rejection and skips remaining tasks.
Examples
const make = (value, ms) => () =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const results = await runSequentially([make("a", 20), make("b", 5)]);
// results === ["a", "b"] — "b" waits for "a", even though it's fasterTasks run strictly one at a time.
try {
await runSequentially([
async () => 1,
async () => { throw new Error("stop"); },
async () => 3, // never runs
]);
} catch (error) {
// error.message === "stop"
}A rejection halts the chain immediately.
What it has to do
- Never have more than one task running at a time.
- Resolve with results in the order the tasks were given.
- Resolve with
[]whentasksis empty. - Reject with the first rejection reason and skip the remaining tasks.
Notes
forEach(async ...)kicks off every task at once — usefor...ofwithawaitto actually serialise.- An empty array must resolve with
[], not reject.
Stuck? The javascript course covers everything this challenge needs.
- 1.resolves with results in task order
- 2.runs only one task at a time
- 3.resolves with an empty array for no tasks
- 4.stops at the first rejection
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.