This content originally appeared on DEV Community and was authored by Bukunmi Odugbesan
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!
This content originally appeared on DEV Community and was authored by Bukunmi Odugbesan
Bukunmi Odugbesan | Sciencx (2025-10-22T23:26:25+00:00) Coding Challenge Practice – Question 33. Retrieved from https://www.scien.cx/2025/10/22/coding-challenge-practice-question-33/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.