3 回答

TA贡献1827条经验 获得超8个赞
Promise.all是全有或全无。它会在阵列中的所有承诺解析后解析,或者在其中一个承诺拒绝后立即拒绝。换句话说,它可以使用所有已解析值的数组进行解析,也可以使用单个错误进行拒绝。
有些库有一些叫做的东西Promise.when,据我所知,它会等待阵列中的所有承诺解析或拒绝,但我不熟悉它,而且它不在ES6中。
你的代码
我同意其他人的意见,你的修复应该有效。它应该使用可能包含成功值和错误对象的数组的数组来解析。在成功路径中传递错误对象是不寻常的,但假设您的代码期望它们,我认为没有问题。
我能想到为什么它“无法解决”的唯一原因是它没有显示我们没有向你展示的代码,以及你没有看到任何关于这个的错误消息的原因是因为这个承诺链没有终止赶上(至于你向我们展示的东西)。
我冒昧地将你的例子中的“现有链”分解出来并用一个捕获来终止链。这可能不适合你,但对于阅读本文的人来说,重要的是始终返回或终止链,或者潜在的错误,甚至是编码错误,都会被隐藏(这是我怀疑在这里发生的事情):
Promise.all(state.routes.map(function(route) {
return route.handler.promiseHandler().catch(function(err) {
return err;
});
}))
.then(function(arrayOfValuesOrErrors) {
// handling of my array containing values and/or errors.
})
.catch(function(err) {
console.log(err.message); // some coding error in handling happened
});

TA贡献1799条经验 获得超8个赞
为了继续Promise.all
循环(即使Promise拒绝),我写了一个被调用的实用函数executeAllPromises
。此实用程序函数返回带有results
和的对象errors
。
我们的想法是,你传递给的所有executeAllPromises
Promise都将被包装成一个永远解决的新Promise。新的Promise解决了一个有2个点的阵列。第一个点保存解析值(如果有的话),第二个点保留错误(如果包装的Promise拒绝)。
作为最后一步,executeAllPromises
累积包装的promises的所有值,并返回带有数组的最终对象results
和数组errors
。
这是代码:
function executeAllPromises(promises) { // Wrap all Promises in a Promise that will always "resolve" var resolvingPromises = promises.map(function(promise) { return new Promise(function(resolve) { var payload = new Array(2); promise.then(function(result) { payload[0] = result; }) .catch(function(error) { payload[1] = error; }) .then(function() { /* * The wrapped Promise returns an array: * The first position in the array holds the result (if any) * The second position in the array holds the error (if any) */ resolve(payload); }); }); }); var errors = []; var results = []; // Execute all wrapped Promises return Promise.all(resolvingPromises) .then(function(items) { items.forEach(function(payload) { if (payload[1]) { errors.push(payload[1]); } else { results.push(payload[0]); } }); return { errors: errors, results: results }; });}var myPromises = [ Promise.resolve(1), Promise.resolve(2), Promise.reject(new Error('3')), Promise.resolve(4), Promise.reject(new Error('5'))];executeAllPromises(myPromises).then(function(items) { // Result var errors = items.errors.map(function(error) { return error.message }).join(','); var results = items.results.join(','); console.log(`Executed all ${myPromises.length} Promises:`); console.log(`— ${items.results.length} Promises were successful: ${results}`); console.log(`— ${items.errors.length} Promises failed: ${errors}`);});
添加回答
举报