Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【手写篇 - Day 03】实现Promise.allSettled() #3

Open
MarsPen opened this issue Mar 24, 2022 · 1 comment
Open

【手写篇 - Day 03】实现Promise.allSettled() #3

MarsPen opened this issue Mar 24, 2022 · 1 comment

Comments

@MarsPen
Copy link
Owner

MarsPen commented Mar 24, 2022

题目描述

Promise.allSettled()方法返回一个在所有给定的 promise 都已经 fulfilled rejected 后的 promise,并带有一个对象数组,每个对象表示对应的 promise 结果。

Promise.all() 不同,Promise.allSettled() 会等待所有的 promise 直到 fulfill 或者 reject

@MarsPen MarsPen changed the title 【手写篇 - Day03】实现Promise.allSettled() 【手写篇 - Day 03】实现Promise.allSettled() Mar 25, 2022
@MarsPen
Copy link
Owner Author

MarsPen commented Apr 3, 2022

思路

  • 参数为一个可迭代的对象,其中每个成员都是 promise
  • 返回给定 promise 的 fulfilled 或 rejected,并带有一个数组,数组中每个对象都表示对应的 promise

代码

function allSettled(promises) {
    // 如果传入的参数为空,那么返回一个空的 Promise
  if (promises.length === 0) {
    return Promise.resolve([])
  }

  // 匹配传入的参数,如果是 Promise 对象,那么就返回 Promise 对象
  let promisesIterable = promises.map((item)=>{
    return item instanceof Promise ? item : Promise.resolve(item)
  })

  // 创建一个数组,用来存储所有的 Promise 的状态
  let results = []
  // 用来记录当前已经完成的 Promise 的数量
  let completed = 0
  return new Promise((resolve, rejected) => {
    // 循环遍历传入的参数,并且创建一个 Promise
    for (let i=0; i < promisesIterable.length; i++) {
      Promise.resolve(promisesIterable[i])
      .then((value)=>{
        results[i] = {status: 'fulfilled', value}
      })
      .catch((reason)=>{
        results[i] = {status: 'rejected', reason}
      })
      .finally(()=>{
        // 当所有的 Promise 都完成的时候,返回结果  并且调用 resolve
        completed++
        if (completed === promisesIterable.length) {
          resolve(results)
        }
      })
    }
  })
}

补充知识

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant