LearnFrenzy
Sign in Take a free test

Callbacks · Callbacks Coding Problems · Question 3

Run tasks in parallel and keep the results in order in JavaScript Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Write parallel(tasks, done) that starts all callback tasks at once, stores each result at its task's index and calls done once when every task has finished (or once with the first error).

Solution
main.js
function parallel(tasks, done) {
  const results = new Array(tasks.length);
  let pending = tasks.length, finished = false;
  if (pending === 0) return done(null, results);
  tasks.forEach((task, i) => {
    task((err, value) => {
      if (finished) return;                     // ignore late callbacks after an error
      if (err) { finished = true; return done(err); }
      results[i] = value;
      if (--pending === 0) { finished = true; done(null, results); }
    });
  });
}

const fetchPrice = (item, ms, price) => (cb) => setTimeout(() => cb(null, `${item}: ₹${price}`), ms);
parallel([fetchPrice("laptop", 30, 54999), fetchPrice("mouse", 5, 499), fetchPrice("bag", 15, 1299)], (err, prices) => console.log(prices.join(" | ")));

Output Verified by running it on Node.js

laptop: ₹54999 | mouse: ₹499 | bag: ₹1299

All tasks run at the same time (total ≈ 30 ms instead of 50 ms). Writing results[i] keeps request order regardless of finish order; the finished flag makes done run exactly once.

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