我正在寻找从promise数组获得解析和拒绝的方法。我目前指望蓝鸟实施,因此ES6兼容解决方案也适合。
最让人想到的是使用Bluebird的Promise.settle
,我认为承诺检查是不必要的复杂问题:
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%履行率不是选项或目标的情况来说,这似乎是一项微不足道的任务,但我甚至不知道食谱的名称。
在Bluebird或其他承诺实现中是否有一种简洁且经过充分验证的方法来处理此问题 - 内置运算符或扩展?
答案 0 :(得分:4)
自OP提出以来,为完整性添加了答案。这是我要做的:
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
]);
答案 1 :(得分:3)
没有内置任何东西,但reduce
可以使它非常简洁:
Promise
.settle(promises)
.reduce(([resolved, rejected], inspection) => {
if (inspection.isFulfilled())
resolved.push(inspection.value());
else
rejected.push(inspection.reason());
return [resolved, rejected];
}, [[], []]);
答案 2 :(得分:1)
您可以使用Promise.all()
,处理被拒绝的Promise
,return
reason
或其他值来链接.then()
let promises = [
Promise.resolve("resolved"),
Promise.resolve("resolved"),
Promise.reject("rejected")
]
, results = {resolved:[], rejected:[]}
, resolvedAndRejected = Promise.all(
promises.map((p) => {
return p.then((resolvedValue) => {
results.resolved.push(resolvedValue);
return resolvedValue
}, (rejectedReason) => {
results.rejected.push(rejectedReason);
return rejectedReason
})
}));
resolvedAndRejected.then((data) => {
console.log(data, results)
});