Home
← All questions

Run Async Tasks Sequentially with Results and Error Handling in JavaScript

EasyPremiumJavaScript

Asked at SumoLogic · Forward Networks

JavaScript interview practice: Start each job only after the previous one finishes. Capture success and failure for every job; do not stop when one rejects.

Problem

You have a list of async jobs — for example applying migrations, or uploading files that must land in order. The next job should start only after the previous one has finished. You still want a record of 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
}
Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium