手动实现Promise.all()方法

手动实现Promise.all()函数是面试中常做的现场coding考察,那么如何实现呢?我们先来看看Promise.all()的用法。

1
2
3
Promise.all([p1, p2, p3]).then(result => {
console.log(result)
})

Promise.all()方法接受一个数组为参数,数组中是promise,如果数组中的promise都是resolve状态,那么Promise.all()正常返回resolve,返回的数据为一个数组,就是参数中每个promise的结果组成的数组。如果promise.all()中任何一个是reject,那么promise.all()直接reject。
所以Promise.all()的特点可以总结为:

  • 1、接收一个 Promise 实例的数组或具有 Iterator 接口的对象,

  • 2、如果元素不是 Promise 对象,则使用 Promise.resolve 转成 Promise 对象

  • 3、如果全部成功,状态变为 resolved,返回值将组成一个数组传给回调

  • 4、只要有一个失败,状态就变为 rejected,返回值将直接传递给回调all() 的返回值也是新的 Promise 对象

来看具体代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//  假设我们已经实现了_Promise
_Promise.prototype.all = (promiseList) => {
return new _Promise((resolve, reject) => {
if (!Array.isArray(promiseList)) {
reject(new TypeError('参数错误!'))
}
let count = 0
let valueList = new Array(promiseList.length)
promiseList.forEach((promise, index) => {
_Promise.resolve(promise).then(result => {
count++
valueList[index] = result // 将每次返回的结果搜集起来
if (count === promiseList.length) {
// 表示所有的promise都有结果,最终将所有的结果都resolve出去
resolve(valueList)
}
}, err => reject(err))
})
})
}

看看,其实很简单。

  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2022 Lee
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信