美文网首页
Promise.allSettled 实现原理

Promise.allSettled 实现原理

作者: 前端青音 | 来源:发表于2020-05-13 10:12 被阅读0次
    
    Promise.allSettled = function (list) {
        if (list instanceof Array) {
            let ret = [];
            list.forEach((i) => {
                ret.push(
                    new Promise(function (resolve, reject) {
                        i.then((v) => {
                            resolve({ state: true, data: v });
                        }).catch((e) => {
                            resolve({ state: false, data: e });
                        });
                    })
                );
            });
            return Promise.all(ret);
        }
        return Promise.reject();
    };
    
    // 简单测试
    
    function rand() {
        return new Promise(function (resolve, reject) {
            let ret = parseInt(Math.random() * 100);
            console.log(ret, ret % 1)
            if (ret%2 === 0) {
                resolve(ret);
            } else {
                reject(ret);
            }
        });
    }
    
    
    
    // test
    
    let list = [];
    for (let i = 10; i > 0; i--) {
        list.push(rand());
    }
    Promise.allSettled(list).then(v => console.log(v))
    

    相关文章

      网友评论

          本文标题:Promise.allSettled 实现原理

          本文链接:https://www.haomeiwen.com/subject/wmwgnhtx.html