Wait until all promises complete even if some rejected

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

    I had the same problem and have solved it in the following way:

    const fetch = (url) => {
      return node-fetch(url)
        .then(result => result.json())
        .catch((e) => {
          return new Promise((resolve) => setTimeout(() => resolve(fetch(url)), timeout));
        });
    };
    
    tasks = [fetch(url1), fetch(url2) ....];
    
    Promise.all(tasks).then(......)
    

    In that case Promise.all will wait for every Promise will come into resolved or rejected state.

    And having this solution we are "stopping catch execution" in a non-blocking way. In fact, we're not stopping anything, we just returning back the Promise in a pending state which returns another Promise when it's resolved after the timeout.

提交回复
热议问题