JavaScript Promise.all有一个回调,当成功和失败时触发 [英] Does JavaScript Promise.all have a callback that is fired when there are success AND failures
问题描述
这是我以为我认为: / strong>
Promise.all需要一系列承诺。
如果所有的承诺成功,那么 c $ c>回调正在运行。
如果其中一个承诺失败,则$ code> .catch callback被调用,传入的参数是单个引发的错误的值。
没有回调,这是所有的结果如果一些成功,一些失败的承诺。即它不能给你一个数组(伪代码) [成功,失败,成功,成功]
- 像一个人会期望的,可以在许多JS库中找到(ajax ,ember等)。
这就像 .then
更像是一个。成功
,而不是始终运行所有承诺之后的功能,无论是否成功或某些失败。为什么没有。当
.finally
.runThisShizNoMatterWhat
??或者我错过了一些东西(很可能)?
var someThings = [...]; //可能成功或失败的一些承诺列表
结算(someThings).then(results => {
results.forEach(result => {
if(result.state = =='fullfilled'){
console.log('succeeded',result.value);
} else {
console.log('failed',result.value);
}
});
});
函数sett(arr){
return Promise.all(arr.map(promise => {
return promise.then(
value = {({state:'fullfilled',value}),
value =>({state:'rejected',value})
);
}));
}
Am I misunderstanding Promise.all? I have X promises in an array and i'm trying to aggregate the success/failure ratio of the array.
Here is what I think I know:
Promise.all takes an array of promises.
If all of the promises succeed then the .then
callback is ran.
If one of the promises fail then the .catch
callback is called and the argument passed in is the value of the single raised error.
There is no callback fired which is the result of all the promises if some succeed and some fail. I.e. it can't give you an array like (pseudo code) [success, fail, success, success]
- like one would expect and one can find in many JS libraries (ajax, ember, etc).
It's like the .then
is more like a .success
, not a function that always runs after all the promises are fulfilled regardless of whether some succeeded or some failed. Why doesn't have a .when
.finally
.runThisShizNoMatterWhat
?? Or am I missing something (very probable)?
This is related to Bluebird Promise.all - multiple promises completed aggregating success and rejections, but that's Bluebird-specific. The core of the issue is that if you want to inspect whether something succeeded or failed, then you aren't really asking for the direct result of each promise. Instead, you'd want to transform the promises before using Promise.all
. There is no helper for this ES6-standard promises, but it is trivial to implement. In most libraries, this is known as Promise.settle
. For example
var someThings = [...]; // some list of promises that may succeed or fail
settle(someThings).then(results => {
results.forEach(result => {
if (result.state === 'fullfilled'){
console.log('succeeded', result.value);
} else {
console.log('failed', result.value);
}
});
});
function settle(arr){
return Promise.all(arr.map(promise => {
return promise.then(
value => ({state: 'fullfilled', value}),
value => ({state: 'rejected', value})
);
}));
}
这篇关于JavaScript Promise.all有一个回调,当成功和失败时触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!