3 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個贊
Promise.all是全有或全無。它會在陣列中的所有承諾解析后解析,或者在其中一個承諾拒絕后立即拒絕。換句話說,它可以使用所有已解析值的數(shù)組進(jìn)行解析,也可以使用單個錯誤進(jìn)行拒絕。
有些庫有一些叫做的東西Promise.when,據(jù)我所知,它會等待陣列中的所有承諾解析或拒絕,但我不熟悉它,而且它不在ES6中。
你的代碼
我同意其他人的意見,你的修復(fù)應(yīng)該有效。它應(yīng)該使用可能包含成功值和錯誤對象的數(shù)組的數(shù)組來解析。在成功路徑中傳遞錯誤對象是不尋常的,但假設(shè)您的代碼期望它們,我認(rèn)為沒有問題。
我能想到為什么它“無法解決”的唯一原因是它沒有顯示我們沒有向你展示的代碼,以及你沒有看到任何關(guān)于這個的錯誤消息的原因是因?yàn)檫@個承諾鏈沒有終止趕上(至于你向我們展示的東西)。
我冒昧地將你的例子中的“現(xiàn)有鏈”分解出來并用一個捕獲來終止鏈。這可能不適合你,但對于閱讀本文的人來說,重要的是始終返回或終止鏈,或者潛在的錯誤,甚至是編碼錯誤,都會被隱藏(這是我懷疑在這里發(fā)生的事情):
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貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超8個贊
為了繼續(xù)Promise.all
循環(huán)(即使Promise拒絕),我寫了一個被調(diào)用的實(shí)用函數(shù)executeAllPromises
。此實(shí)用程序函數(shù)返回帶有results
和的對象errors
。
我們的想法是,你傳遞給的所有executeAllPromises
Promise都將被包裝成一個永遠(yuǎn)解決的新Promise。新的Promise解決了一個有2個點(diǎn)的陣列。第一個點(diǎn)保存解析值(如果有的話),第二個點(diǎn)保留錯誤(如果包裝的Promise拒絕)。
作為最后一步,executeAllPromises
累積包裝的promises的所有值,并返回帶有數(shù)組的最終對象results
和數(shù)組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}`);});
添加回答
舉報(bào)