DEV Community

jser
jser

Posted on • Edited on

BFE.dev #34. implement `Promise.any()`

BFE.dev is like a LeetCode for Front End developers. I’m using it to practice my skills.

Alt Text

This article is about the coding problem BFE.dev#34. implement Promise.any()

Analysis

AS MDN says,

Promise.any() takes an iterable of Promise objects and, as soon as one of the promises in the iterable fulfils, returns a single promise that resolves with the value from that promise
e item one by one randomly from rest possible positions.

We can follow the definition and create a new Promise that resolves when any promise passed in resolves.

Problem is when all promises reject, we need an array to hold all the errors, and finally reject the returned promise by counting.

Show me the code


/**
 * @param {Array<Promise>} promises
 * @returns {Promise}
 */
function any(promises) {
  // return a Promise, which resolves as soon as one promise resolves
  return new Promise((resolve, reject) => {
    let isFulfilled = false
    const errors = []
    let errorCount = 0
    promises.forEach((promise, index) => promise.then((data) => {
      if (!isFulfilled) {
        resolve(data)
        isFulfilled = true
      }
    }, (error) => {
      errors[index] = error
      errorCount += 1

      if (errorCount === promises.length) {
        reject(new AggregateError('none resolved', errors))
      }
    }))
  })
}
Enter fullscreen mode Exit fullscreen mode

Passed

Alt Text

Here is my video explaining: https://www.youtube.com/watch?v=fYTmLpFJPdw

Hope it helps, you can have a try at here

Top comments (0)