1. Promise.all实现
Promise.all = function(promises) {
var values = new Array(promises.length); // 保存成功value的数组
var resolvedCount = 0;
return new Promise((resolve, reject) => {
promises.forEach((p, index) => {
Promise.resolve(p).then(
value => {
resolvedCount ++;
values[index] = value;
if (resolvedCount === promises.length) {
resolve(values);
}
},
reason => {
reject(reason);
}
)
})
})
}
2. Promise.race实现
Promise.race = function(promises) {
return new Promise((resolve, reject) => {
promises.forEach((p, index) => {
Promise.resolve(p).then(
value => {
resolve(value);
},
reason => {
reject(reason)
}
)
})
})
}