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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!