Open ForeveHG opened 5 years ago
实现原理:
function myAll(iterator) {
return new Promise((resolve, reject) => {
[].reduce.call(iterator, function (result, p, index) {
Promise.resolve(p).then(res => {
result[index] = res
let keys = Object.keys(result);
if (keys.length == iterator.length) {
let arr = [];
keys.forEach(i => arr[i] = result[i])
resolve(arr)
}
})
return result;
}, {})
})
}
Promise.all函数接收一个遍历器对象做参数,Promise.all返回一个promise实例,Promise.all会将遍历器对象中的每一项转换为Promise对象,等遍历器对象的每项promise都决议后,这个promise实例才决议,只有当遍历器对象每项promies都决议为resolve,promise实例才决议为resolve,如果有一项决议为reject了,promise实例就决议为reject