Wait until all promises complete even if some rejected

前端 未结 18 1916
醉酒成梦
醉酒成梦 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:45

    Instead of rejecting, resolve it with a object. You could do something like this when you are implementing promise

    const promise = arg => {
      return new Promise((resolve, reject) => {
          setTimeout(() => {
            try{
              if(arg != 2)
                return resolve({success: true, data: arg});
              else
                throw new Error(arg)
            }catch(e){
              return resolve({success: false, error: e, data: arg})
            }
          }, 1000);
      })
    }
    
    Promise.all([1,2,3,4,5].map(e => promise(e))).then(d => console.log(d))

提交回复
热议问题