HomePremium · ₹1199
← All questions

Run async tasks sequentially, collecting results and errors

Easy
Asked at:SumoLogicForward Networks
Was this asked in an interview?

Execute an array of async task functions one after another, collecting every outcome without short-circuiting.

Problem

You have a list of async jobs — say, apply a series of DB migrations, or upload files that must land in order. They must run one at a time (the next only starts after the previous finishes), and you want to record every outcome, including failures, without stopping at the first error.

Implement runSequentially(tasks) where tasks is an array of functions each returning a promise. It runs them in order and resolves with an array of outcome objects:

  • { status: "fulfilled", value } on success, or
  • { status: "rejected", reason } on failure.

A failing task must not stop the ones after it.

Input

const tasks = [
  () => Promise.resolve(1),
  () => Promise.reject("fail"),
  () => Promise.resolve(3),
];
runSequentially(tasks).then(console.log);

Expected output

[
  { status: "fulfilled", value: 1 },
  { status: "rejected", reason: "fail" },
  { status: "fulfilled", value: 3 },
]

Implement:

async function runSequentially(tasks) {
  // Your code here
}
Run async tasks sequentially, collecting results and errors — JavaScript Interview Question | Mentoxis