LearnFrenzy
Sign in Take a free test

Callbacks · Callbacks Coding Problems · Question 2

Run asynchronous tasks one after another in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Write series(tasks, done) that runs callback-based tasks one at a time, in order, and calls done with all results (or the first error).

Solution
main.js
function series(tasks, done) {
  const results = [];
  const next = (i) => {
    if (i === tasks.length) return done(null, results);
    tasks[i]((err, value) => {
      if (err) return done(err);
      results.push(value);
      next(i + 1);                 // start the next task only when this one has finished
    });
  };
  next(0);
}

const task = (name, ms) => (cb) => setTimeout(() => { console.log("finished", name); cb(null, name.toUpperCase()); }, ms);
series([task("login", 20), task("load", 5), task("render", 10)], (err, res) => console.log("results:", res.join(" → ")));

Output Verified by running it on Node.js

finished login
finished load
finished render
results: LOGIN → LOAD → RENDER

next(i) starts task i only after task i − 1 called back, so the slower first task still finishes first. Errors stop the chain immediately.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links