前端剑解之手写Promise.all

49 阅读1分钟

Promise.myAll = function (iterableObj) {

return new Promise((resolve, reject) => {

    let count = 0;
    let result = []
    let doneCount = 0;
    for (const item of iterableObj) {
        //先存一个index
        let index = count;

        Promise.resolve(item).then(res => {
            //然后再这里进行访问,实际这里就是一个闭包
            //闭包:可以在函数的外部访问到函数内部的局部变量。
            console.log(index, 'index')
            result[index] = res;
            doneCount += 1
            if (doneCount === count) {
                resolve(result)
            }

        }).catch(reject)

        count += 1


    }


})

}

const pro1 = new Promise((resolve, reject) => {


    setTimeout(() => {
        resolve(1)
    }, 2000)

})

const pro2 = 'hello';

Promise.myAll([pro1, pro2]).then(res => {
    console.log(res,'myAll')
})
Promise.all([pro1, pro2]).then(res => {

    console.log(res,'all')
})

image.png

解析:iterableObj 为一个可迭代对象 Map Set都是可迭代对象 许多jy喜欢forEach来实现Promise.all 实际是不理想的,因为有些可迭代对象没有length,像Map,Set只有size属性,所以最好使用for of来遍历可迭代对象。 Promise.all里面的数据是根据顺序返回的,所以我们要根据索引来进行添加数据,但是for of没有索引,我们可以使用闭包来获取索引 实际就是保存cuout之前的值作为索引,最后我们要等所有promise对象完成之后,也就是count===doneCount相等,再返回所有数据也就是我们的res。