call(back)
FrontendmediumSign in to star problems

Run Promises in Sequence

Execute an array of asynchronous tasks one after another.

Clarify the input first. A promise starts its work when it is created, so an array of promises is already running in parallel. Sequencing needs an array of tasks: functions that each return a promise.

Implement runInSequence(tasks): call each task only after the previous one has settled. Resolve with the results in task order. If a task rejects, reject with that reason and never start the tasks after it. An empty list resolves to [].

The grader runs your code on a virtual clock. Tasks record when they start and settle, so the checks see exactly when each one ran.

Hints

Hint 1

The shortest correct version is a for...of loop that awaits each task() and pushes the result. A rejection throws out of the loop, so later tasks never start.

Hint 2

The pre-async version reduces into a chain: start from Promise.resolve([]), and have each step call the task inside the previous step's .then.

Asked at