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

promise.all 实现 #36

Open
keep-run opened this issue May 20, 2021 · 0 comments
Open

promise.all 实现 #36

keep-run opened this issue May 20, 2021 · 0 comments

Comments

@keep-run
Copy link
Owner

简介

promise的地位不言而喻,凡是需要异步处理的现在基本都在使用promise; promise的出现解决了异步处理中回调地狱的问题,使得开发者可以使用同步的方式去写异步逻辑。开发体验得到极大的提升;同时Promise还提供了很多有用的工具函数。 这里着重说一下Promise.all方法;

功能

Promise.all实现将多个Promise实例包装成一个的功能。

  • 接受一个数组作为参数,每一项为一个Promise实例,如果不是,内部会用Promise.resolve转化。
  • 参数中的每个Promisereslove时,Promise.allreslove。且返回的顺序和参数顺序一致(可以保证多个异步任务返回的顺序),其中一个失败时,整体失败,返回失败的那个实例数据。

简单实现

function PromiseAll(promises = []) {
  return new Promise((resolve, reject) => {
    if (!Array.isArray(promises)) {
      reject('PromiseAll 参数必须为数组')
    }
    let resloveNum = 0 //记录reslove的个数
    const promisesLength = promises.length
    const result = []
    promises.forEach((item, index) => {
      let actionItem = item
      // 如果不是promise实例,使用Promise.resolve转换成 Promise 实例
      if (!(item instanceof Promise)) {
        actionItem = Promise.resolve(item)
      }
      actionItem.then(res => {
        resloveNum++;
        result[index] = res  //确保返回顺序和参数顺序一致
        if (resloveNum === promisesLength) {
          resolve(result)
        }
      }).catch(res => {
        reject(res)
      })
    })
  })
}

测试

const p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(1)
  }, 1000)
})
const p2 = 2
const p3 = Promise.resolve(3)
const p4 = Promise.reject(4)
PromiseAll([p1, p2, p3]).then((res) => {
  console.log('resolve',res)   
}).catch(res => {
  console.log('catch', res)
})
// 1秒后输出 resolve [1,2,3]

PromiseAll([p2, p3, p4]).then((res) => {
  console.log('resolve', res)   
}).catch(res => {
  console.log('catch', res)
})
// 输出 catch 4
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