The task is to implement the race() function, which works like the Promise.race(), but for callback asynchronous functions.
The boilerplate code:
function race(funcs){
// your code here
}
Each function in the funcs is an asynchronous function that accepts a callback. A new function is returned, which triggers all the functions when invoked with a callback. As soon as one of the functions finishes, it calls the callback and ignores the rest.
Keep an indicator to ensure that the callback is called once.
let finished = false;
Loop through the array of async functions. Call each function, passing a wrapper callback. The wrapper checks if finished is true or false.
funcs.forEach(fn => {
fn((err, result) => {
if (!finished) {
finished = true;
callback(err, result);
}
});
})
If finished is false, the callback is triggered. If otherwise, the callback is ignored.
The final code:
function race(funcs) {
return function (callback) {
let finished = false;
funcs.forEach(fn => {
fn((err, result) => {
if (!finished) {
finished = true;
callback(err, result);
}
});
});
};
}
That's all folks!
Top comments (0)