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
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(" → ")));
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!