AniUI Academy

Run async tasks one after another

easyAsync & Promises+150 XPPractice

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 faster

Tasks 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 [] when tasks is empty.
  • Reject with the first rejection reason and skip the remaining tasks.

Notes

  • forEach(async ...) kicks off every task at once — use for...of with await to actually serialise.
  • An empty array must resolve with [], not reject.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
4 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.