The task is to implement a race() function that works like Promise.race().
The boilerplate code
function race(promises) {
// your code here
}
The Promise.race() function returns a promise that resolves or rejects as soon as any of the input promises settle.
To recreate that, a new promise is created and returned
return new Promise((resolve, reject) => {
}
Then, each of the promises is looped through
for(const p of promises) {
}
Using promise.resolve, each of them is converted into a real promise, and then resolved or rejected immediately the first one settles.
Promise.resolve(p).then(resolve, reject)
The final code
function race(promises) {
return new Promise((resolve, reject) => {
for(const p of promises) {
Promise.resolve(p).then(resolve, reject)
}
})
}
That's all folks!
Top comments (0)