使用
var promise1 = Promise.resolve(3);
var promise2 = 42;
var promise3 = new Promise(function(resolve, reject) {
setTimeout(resolve, 100, 'foo');
});
Promise.all([promise1, promise2, promise3]).then(function(values) {
console.log(values);
});
分析
1.参数为iterator类型
2.并发执行
3.等待所有promise返回后才返回结果
4.结果为数组,与传入的promise顺序对应
5.但凡有一个出错,则抛错
实现
Promise.myAll = function (Iterator) {
return new Promise((resolve, reject) => {
// 转换成数组,好处是方便获取长度,且方便对应结果数组的index
const arr = Array.from(Iterator);
const { length } = arr;
const result = [];
// 无length则无法执行for of,所以此处特殊值处理
if (!length) return result;
//计数,个数达到length即全部执行完
let count = 0;
for (let index = 0; index < length; index++) {
const promise = arr[index];
promise
.then((res) => {
result[index] = res;
if (++count === length) resolve(result);
})
.catch((err) => {
reject(err);
});
}
});
};
测试案例
const test = async () => {
var promise1 = Promise.resolve(3);
var promise2 = Promise.resolve({ name: "shuaige" });
var promise3 = new Promise(function (resolve, reject) {
setTimeout(resolve, 100, "foo");
});
Promise.myAll([promise3, promise1, promise2]).then(function (values) {
console.log(values);
});
};
test();
//[
///"foo",
//3,
//{ name: "shuaige" }
//]