ForeveHG / Frontend-Daily-Interview

学习,尝试回答一些前端面试题
1 stars 0 forks source link

14. 介绍下 Promise.all 使用、原理实现及错误处理 #14

Open ForeveHG opened 5 years ago

ForeveHG commented 4 years ago

Promise.all函数接收一个遍历器对象做参数,Promise.all返回一个promise实例,Promise.all会将遍历器对象中的每一项转换为Promise对象,等遍历器对象的每项promise都决议后,这个promise实例才决议,只有当遍历器对象每项promies都决议为resolve,promise实例才决议为resolve,如果有一项决议为reject了,promise实例就决议为reject

ForeveHG commented 4 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;
        }, {})
    })
}