![](/img/trans.png)
[英]JavaScript: Promise.All() and Async / Await and Map()
[英]async await Promise.all with chain
我有一些我想做一個promise的promise函數。 但是我不確定當其中一個存在“ then”鏈時該怎么做。
例如。
Promise.all([
promiseFn1(),
promiseFn2().then(promiseFn3)
])
當Promise.all
鏈接Promise.all
promiseFn2()
時,我將如何實現異步等待?
我正在考慮制作一個煩人的函數,但不希望這樣做:
await Promise.all([
promise1.fn(),
(() =>{
p2response = await promise2Fn();
return promise3Fn(p2response);
})()
])
是的,立即執行的async
函數表達式可以做到這一點:
await Promise.all([
promise1.fn(),
(async () => promise3Fn(await promise2Fn()) )()
])
但是,我建議保留更簡單的.then()
調用。 並不是任何強迫您await
任何地方使用的東西……
另外,如果您正在尋找簡潔的代碼( then
鏈並不像您的示例中那樣簡單,而是涉及函數表達式),則只需使用一個命名的輔助函數:
async function promise2and3fn() {
return promise3Fn(await promise2Fn());
}
await Promise.all([
promise1.fn(),
promise2and3fn()
])
當您要同時使用await
時,無法繞開這些額外的函數,因為函數內部的執行始終是順序執行的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.