Promise.all find which promise rejected

前端 未结 2 781
眼角桃花
眼角桃花 2021-02-05 16:31

In my code, I am using Promise.all() to run code asynchronously once some promises have all fulfilled. Sometimes, one promise will fail, and I\'m not sure why.

2条回答
  •  醉酒成梦
    2021-02-05 16:59

    this wrapper will wait for and return every result and/or rejection

    the returned array will be objects

    { // this one resolved
        ok: true,
        value: 'original resolved value'
    },
    { // this one rejected
        ok: false,
        error: 'original rejected value'
    },
    { // this one resolved
        ok: true,
        value: 'original resolved value'
    },
    // etc etc
    

    One caveat: this will wait for ALL promises to resolve or reject, not reject as soon as the first rejection occurs

    let allresults = function(arr) {
        return Promise.all(arr.map(item => (typeof item.then == 'function' ? item.then : Promsie.resolve(item))(value => ({value, ok:true}), error => ({error, ok:false}))));
    }
    
    allresults(arrayOfPromises)
    .then(results => {
        results.forEach(result => {
            if(result.ok) {
                //good
                doThingsWith(result.value);
            } else {
                // bad
                reportError(result.error);
            }
        });
    });
    

提交回复
热议问题