DEV Community

jser
jser

Posted on • Edited on

BFE.dev #33. implement Promise.allSettled()

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#33. implement Promise.allSettled()

Analysis

Different from Promise.all() which rejects right away once an error occurs, Promise.allSettled() waits for all promises to settle.

So we just need to keep track of all the promises, by using an array. Promises might settle in arbitrary order, so use index to set the right location.

Show me the code

First start with the basic skeleton of new Promise.

function allSettled(promises) {

  return new Promise((resolve, reject) => {
    const result = []

    promises.forEach((promise, index) => {
      promise.then((value) => {
        result[index] = {
          status: 'fulfilled',
          value
        }
      }, (reason) => {
        result[index] = {
          status: 'rejected',
          reason
        }
      })
    })
  })
}
Enter fullscreen mode Exit fullscreen mode

Then we need to resolve when all promises are settled, so use a counter to achieve this.

And also notice that the input might contain non-Promises.

function allSettled(promises) {
  if (promises.length === 0) return Promise.resolve([])

  const _promises = promises.map(
    item => item instanceof Promise ? item : Promise.resolve(item)
    )

  return new Promise((resolve, reject) => {
    const result = []
    let unSettledPromiseCount = _promises.length

    _promises.forEach((promise, index) => {
      promise.then((value) => {
        result[index] = {
          status: 'fulfilled',
          value
        }

        unSettledPromiseCount -= 1
        // resolve after all are settled
        if (unSettledPromiseCount === 0) {
          resolve(result)
        }
      }, (reason) => {
        result[index] = {
          status: 'rejected',
          reason
        }

        unSettledPromiseCount -= 1
        // resolve after all are settled
        if (unSettledPromiseCount === 0) {
          resolve(result)
        }
      })
    })
  })
}
Enter fullscreen mode Exit fullscreen mode

Passed

This is a fairly simple problem.

Alt Text

Hope it helps, you can have a try at here

Top comments (0)