简体   繁体   English

筛选/恢复Promise.all结果

[英]Filter/recover Promise.all result

Ex: 例如:

function myFunc(args ...){
  ...
  return Promise.all(myPromisesArray)
}

If a promise inside myPromisesArray fails, i will only get the rejection reason in the return value. 如果myPromisesArray内部的myPromisesArray失败,我只会在返回值中得到拒绝原因。

Is there a way to recover all the other resolved values? 有没有办法恢复所有其他解析的值?

If you're using Q, then there's a function called Q.allSettled that basically does what you ask for. 如果您使用的是Q,那么有一个名为Q.allSettled的函数基本上Q.allSettled您的要求。

Otherwise, this simple function will give you the results of all promises, and tell you whether the succeeded or failed. 否则,此简单函数将为您提供所有承诺的结果,并告诉您成功还是失败。 You can then do whatever you need to do with the promises that succeeded or failed. 然后,您可以对成功或失败的承诺做任何需要做的事情。

 /** * When every promise is resolved or rejected, resolve to an array of * objects * { result: [ Promise result ], success: true / false } **/ function allSettled(promises) { return Promise.all( promises.map( promise => promise.then( // resolved (result) => ({ result: result, success: true }), // rejected (result) => ({ result: result, success: false }) ) ) ); } // example usage: const one = Promise.resolve(1); const two = Promise.reject(2); const three = Promise.resolve(3); allSettled([ one, two, three ]) .then((results) => { console.log(results[0]); // { result: 1, success: true } console.log(results[1]); // { result: 2, success: false } console.log(results[2]); // { result: 3, success: true } }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM