问题描述
我正在寻找从promise数组获得解析和拒绝的方法。我目前依赖Bluebird实现,因此ES6兼容解决方案也适用。
I'm looking for the way to get both resolutions and rejections from promise array. I'm currently counting on Bluebird implementation, so ES6 compatible solution would be suitable, too.
最让人想到的是使用Bluebird的 Promise.settle
为此,我认为承诺检查是不必要的复杂问题:
The best thing that comes to mind is to use Bluebird's Promise.settle
for that, and I consider promise inspections an unnecessary complication here:
let promises = [
Promise.resolve('resolved'),
Promise.resolve('resolved'),
Promise.reject('rejected')
];
// is there an existing way to do this?
let resolvedAndRejected = Promise.settle(promises)
.then((inspections) => {
let resolved = [];
let rejected = [];
inspections.forEach((inspection) => {
if (inspection.isFulfilled())
resolved.push(inspection.value());
else if (inspection.isRejected())
rejected.push(inspection.reason());
});
return [resolved, rejected];
});
resolvedAndRejected.spread((resolved, rejected) => {
console.log(...resolved);
console.error(...rejected);
});
对于100%履约率不是一种选择或者不是一种选择的情况,这看起来很简单目标,但我甚至不知道配方的名称。
It looks like a trivial task for the cases where 100% fulfillment rate isn't an option or a goal, but I don't even know the name for the recipe.
在Bluebird或其他承诺实施中是否有一种简洁且经过充分验证的方法来处理-in运算符或扩展名?
Is there a neat and well-proven way to handle this in Bluebird or other promise implementations - built-in operator or extension?
推荐答案
自OP询问后,添加了完整性的答案。以下是我要做的事情:
Added answer for completeness since OP asked. Here is what I'd do:
const res = Promise.all(promises.map(p => p.reflect())) // get promises
.then(values => [
values.filter(x => x.isFulfilled()).map(x => x.value()), // resolved
values.filter(x => x.isRejected()).map(x => x.reason()) // rejected
]);
这篇关于解决*和*拒绝Bluebird中的所有承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!