DEV Community


Posted on • Updated on #34. implement `Promise.any()` 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 implement Promise.any()


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) {
        isFulfilled = true
    }, (error) => {
      errors[index] = error
      errorCount += 1

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


Alt Text

Here is my video explaining:

Hope it helps, you can have a try at here

Top comments (0)