DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 33

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
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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);
        }
      });
    })
Enter fullscreen mode Exit fullscreen mode

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);
        }
      });
    });
  };
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)