从前有匹马叫代码
心若没有栖息的地方,到哪里都是流浪

Promise.all 特性:

1. 按顺序返回结果数组;

2. 当所有promise完成才返回;

3. 返回第一个报错的promise的信息;

直接上代码:

Promise._all = function(args) {
    var count = 0;
    var len = args.length;
    let results = [];
    return new Promise((resolve, reject) => {
        for (let i = 0; i < len; i++) {
            Promise.resolve(args[i])
                .then(r => {
                    count++;
                    results[i] = r;
                    if (count == len) {
                        resolve(results);
                    }
                })
                .catch(e => {
                    reject(e);
                });
        }
    });
};

var promise1 = new Promise(resolve => setTimeout(resolve.bind(this, 1), 100));
var promise2 = new Promise(resolve => setTimeout(resolve.bind(this, 2), 50));
// var promise2 = new Promise((resolve, reject) =>
//     setTimeout(reject.bind(this, new Error('故意抛出错误')), 200)
// );

Promise._all([promise1, promise2])
    .then(values => {
        console.log('values:', values);
    })
    .catch(e => {
        console.log('error:', e.message);
    });

到此结束

posted on 2021-06-17 19:10  从前有匹马叫代码  阅读(185)  评论(0编辑  收藏  举报