当你想要所有结果而不管任何拒绝时,使用什么代替Promise.all() [英] What to use instead of Promise.all() when you want all results regardless of any rejections

查看:327
本文介绍了当你想要所有结果而不管任何拒绝时,使用什么代替Promise.all()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在node.js项目中使用Bluebird promise库。我有两个操作都返回promises,我想知道两者何时完成,无论是已解决还是被拒绝,我需要两者的返回值。我正在读取多个文件的内容,有些文件可能不存在,这是一个OK条件,所以如果文件没有, fs.readFileAsync()将失败存在,我仍然需要其他读操作的结果。

I'm using the Bluebird promise library in a node.js project. I have two operations that both return promises and I want to know when both are done, whether resolved or rejected and I need the return values from both. I'm reading the contents of multiple files and some of the files may not exist and that's an OK condition, so though fs.readFileAsync() will fail if the file doesn't exist, I still need the results of the other read operation.

Promise.all(p1,p2)将拒绝p1或p2拒绝且我不认为我必须从另一个获取数据。

Promise.all(p1, p2) will reject if either p1 or p2 rejects and I don't think I'll necessarily get the data from the other one.

所有其他Bluebird操作( .some() .any() .settle()等...)最适合这种情况?并且,数据如何传回,以便您可以判断哪些成功,哪些不成功?

Of all the other Bluebird operations (.some(), .any(), .settle(), etc...) which is most appropriate to this situation? And, how is the data passed back such that you can tell which ones succeeded and which ones didn't?

推荐答案

那会确实是 .settle 。 Settle接受一系列承诺,并在解析时为所有承诺返回 PromiseInspection 个实例。然后,您可以检查它们是否已完成或被拒绝并提取其值。

That would be indeed be .settle. Settle takes an array of promises and returns PromiseInspection instances for all of them when they resolve. You can then check if they're fulfilled or rejected and extract their value.

例如:

Promise.settle(['a.txt', 'b.txt'].map(fs.readFileAsync)).then(function(results){
    // results is a PromiseInspetion array
    console.log(results[0].isFulfilled()); // returns true if was successful
    console.log(results[0].value()); // the promise's return value
});

您的用例几乎是 Promise.settle 存在。

Your use case is pretty much what Promise.settle exists for.

这篇关于当你想要所有结果而不管任何拒绝时,使用什么代替Promise.all()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆