Wait until all promises complete even if some rejected

前端 未结 18 1906
醉酒成梦
醉酒成梦 2020-11-21 04:55

Let\'s say I have a set of Promises that are making network requests, of which one will fail:

// http://does-not-exist will throw a TypeError
va         


        
18条回答
  •  执笔经年
    2020-11-21 05:24

    I've been using following codes since ES5.

    Promise.wait = function(promiseQueue){
        if( !Array.isArray(promiseQueue) ){
            return Promise.reject('Given parameter is not an array!');
        }
    
        if( promiseQueue.length === 0 ){
            return Promise.resolve([]);
        }
    
        return new Promise((resolve, reject) =>{
            let _pQueue=[], _rQueue=[], _readyCount=false;
            promiseQueue.forEach((_promise, idx) =>{
                // Create a status info object
                _rQueue.push({rejected:false, seq:idx, result:null});
                _pQueue.push(Promise.resolve(_promise));
            });
    
            _pQueue.forEach((_promise, idx)=>{
                let item = _rQueue[idx];
                _promise.then(
                    (result)=>{
                        item.resolved = true;
                        item.result = result;
                    },
                    (error)=>{
                        item.resolved = false;
                        item.result = error;
                    }
                ).then(()=>{
                    _readyCount++;
    
                    if ( _rQueue.length === _readyCount ) {
                        let result = true;
                        _rQueue.forEach((item)=>{result=result&&item.resolved;});
                        (result?resolve:reject)(_rQueue);
                    }
                });
            });
        });
    };
    

    The usage signature is just like Promise.all. The major difference is that Promise.wait will wait for all the promises to finish their jobs.

提交回复
热议问题