promise - 6.promise.all源码实现

promise.all 的特点就是让所有 promise 并发执行,根据执行个数判断是否执行完毕

  1. 代码实现
function isPromise(x) { // 校验是否是 promise 
    if((typeof x == 'object' && x !== null) || typeof x == 'function') {
        if(typeof x.then == 'function') {
            return true
        }
    }
    return false
}
Promise.all = function(promises) {
    return new Promise((resolve, reject) => {
        let arr = []
        let idx = 0 // 执行个数
        let dealProcess = (val, index) => {
            arr[index] = val
            if(++idx == promises.length) {
                resolve(arr)
            }
        }
        promises.forEach((item, i) => {
            if(isPromise(item)) {
                item.then(y => {
                    dealProcess(y, i)
                }, reject)
            }else {
                dealProcess(item, i)
            }
        });
    })
}
let util = require('util')
let read = util.promisify(fs.readFile)
Promise.all([1, read('./name.txt', 'utf8'), 2, read('./age.txt', 'utf8'), 3]).then(data => {
    console.log(data);
})

你可能感兴趣的:(JavaScript)