Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
12.2. Run async callbacks in parallel and collect the results in order
Medium
Topics
This question is in
12. Callbacks, promises and asyncA dashboard needs three things before it can draw: the user, their projects and their notifications. None of these depends on the others, so asking for them one after another wastes time. Started together, the page waits only as long as the slowest one. But the answers come back in any order, and the page still needs to know which answer is which.
Write runInParallel(tasks, done) in parallel.js. It starts every callback-style task at once, collects the values in task order, and reports once to done.
Signature
function runInParallel(tasks, done) // returns undefinedtasks: an array of functions. Each has the formtask(callback)and callscallback(error, value)when it finishes.done: called once, asdone(null, results)when every task succeeded, ordone(error)at the first failure.- An error is a truthy first argument.
null,undefinedandfalsemean success.
Requirements
- Every task starts during the call, without waiting for any other.
done(null, results)is called as soon as the last task succeeds.results[i]is the value oftasks[i], whatever order they finished in. Falsy values andundefinedare results like any other, and leave no hole in the array.- At the first error,
done(error)is called at once, with the error only, without waiting for the other tasks. doneis called exactly once. Answers after the first error are ignored, and a task that calls back twice counts once (its second call changes nothing).- An empty array calls
done(null, []). - Tasks may call back synchronously, during the
task(callback)call. - The
tasksarray is not changed;resultsis a new array. Two runs at the same time do not share state. runInParallelreturnsundefined.
Examples
const wait = (ms, value) => (callback) => setTimeout(() => callback(null, value), ms);
runInParallel([wait(300, "user"), wait(100, "projects"), wait(200, "notifications")], (error, results) => {
console.log(results);
});
// at 300 ms (not 600): ["user", "projects", "notifications"]const fail = (callback) => setTimeout(() => callback(new Error("offline")), 50);
runInParallel([wait(300, "user"), fail], (error) => console.log(error.message));
// at 50 ms: "offline"; the user's answer at 300 ms is ignoredrunInParallel([wait(10, 0), wait(20, undefined)], (error, results) => console.log(results));
// [0, undefined]Environment
- Plain JavaScript in a browser page; the tests call the global
runInParallelfromparallel.js. - The tests' tasks use
setTimeouton a virtual clock, so no test waits for real time. - Stopping tasks that are still running after an error is out of scope: their answers are just ignored.
- A task that throws instead of calling back is out of scope.
Hints
- Finish order and task order differ. Where should each value go so the order does not matter?
- How do you know that the last task has answered, when any of them could be last?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it
Back to the question
Loading the editor…