Promise.all 实现原理

Promise.prototype.all = function(promises) {
    return new Promise((resolve, reject) => {
        if (!isArray(promises)) {
            return reject(new TypeError('Arguments not Array'));
        }
        let resolves = 0;
        let len = promises.length;
        let result = [];
        for (let p of promises) {
            Promise.resolve(p).then(res => {
                resolves++;
                result.push(res);
                if (resolves === len) {
                    resolve(result);
                }
            }, rej => {
                return rekect(rej);
            })
        }
    })
}

Last updated