Wait until all promises complete even if some rejected

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

    Similar answer, but more idiomatic for ES6 perhaps:

    const a = Promise.resolve(1);
    const b = Promise.reject(new Error(2));
    const c = Promise.resolve(3);
    
    Promise.all([a, b, c].map(p => p.catch(e => e)))
      .then(results => console.log(results)) // 1,Error: 2,3
      .catch(e => console.log(e));
    
    
    const console = { log: msg => div.innerHTML += msg + "
    "};

    Depending on the type(s) of values returned, errors can often be distinguished easily enough (e.g. use undefined for "don't care", typeof for plain non-object values, result.message, result.toString().startsWith("Error:") etc.)

提交回复
热议问题