我的代碼必須呼叫一些 Web 服務。為了加快速度,我想同時進行。但是,這些服務的結果必須在決議之前執行。 Promise.all()這是我當前的代碼:
const awaitors = [];
if (!targetLocation) {
awaitors.push((async function () {
targetLocation = await getStorageLocation(storageID);
})());
}
if (!carrierToMove) {
awaitors.push(/* Another similar call that sets carrierToMove */);
}
await Promise.all(awaitors);
pushCarrierIntoStorage(carrierToMove, targetLocation);
如您所見,我在那里使用了一個自執行的 javascript 函式。這并沒有真正有助于我的代碼的可讀性。有沒有更好的方法來實作它而不會失去并行執行兩個呼叫的能力?
uj5u.com熱心網友回復:
一般來說,目標是通過回傳值而不是依賴于副作用(即在更廣泛的范圍內為變數賦值)來實作這種型別的事情。
const promiseTargetLocation = getStorageLocation(storageID);
const promiseCarrierToMove = anotherSimilarCall();
const [carrierToMove, targetLocation] = await Promise.all([promiseCarrierToMove, promiseTargetLocation];
pushCarrierIntoStorage(carrierToMove, targetLocation);
或者,更簡潔地說:
pushCarrierIntoStorage(...(await Promise.all([anotherSimilarCall(), getStorageLocation(storageID)])));
uj5u.com熱心網友回復:
遺憾的是 IIFE 的主要目的是副作用,我會發現該模式的主要缺點。
相反,您可以這樣做:
const carrierAndStorage = await Promise.all([
carrierToMove ?? getCarrier(someID),
targetLocation ?? getStorageLocation(storageID)
]);
pushCarrierIntoStorage(...carrierAndStorage);
??接線員替換您的if.
如您所見,即使它已經非空,也可以將其包含carrierToMove在獲取的陣列中。Promise.all在這種情況下,它將被轉換為立即決議為該值的承諾。
uj5u.com熱心網友回復:
const awaitors = [];
if (!targetLocation) {
awaitors.push(getStorageLocation(storageID).then(targetLocation => {
// process targetLocation
}));
}
if (!carrierToMove) {
awaitors.push(/* do the same as above */);
}
// by the time this resolves, individual
// requests will be processed:
await Promise.all(awaitors);
pushCarrierIntoStorage(carrierToMove, targetLocation);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/533683.html
下一篇:VueJS方法未定義
