知食记
搜索文档…
实现Promise.all

思路

  1. 1.
    传入的一定是数组
  2. 2.
    Promise.resolve包裹(元素不是 Promise 对象,则使用 Promise.resolve 转成 Promise 对象
  3. 3.
    全部成功,返回resolve
  4. 4.
    只要有一个失败,返回reject

代码

1
function promiseAll(promises) {
2
return new Promise(function(resolve, reject) {
3
if (!isArray(promises)) {
4
return reject(new TypeError('arguments must be an array'));
5
}
6
var resolvedCounter = 0;
7
var promiseNum = promises.length;
8
var resolvedValues = new Array(promiseNum);
9
for (var i = 0; i < promiseNum; i++) {
10
(function(i) {
11
Promise.resolve(promises[i]).then(function(value) {
12
resolvedCounter++
13
resolvedValues[i] = value
14
if (resolvedCounter == promiseNum) {
15
return resolve(resolvedValues)
16
}
17
}, function(reason) {
18
return reject(reason)
19
})
20
})(i)
21
}
22
})
23
}
Copied!
复制链接