簡體   English   中英

為什么在返回 promise 的循環內使用.then() 而不是 async/await?

[英]Why to use .then() rather than async/await inside loop that returns promise?

我遇到了多篇關於如何從循環中正確推送新承諾的文章,該循環在新的 promise 中執行多個 API 調用到一個數組中。
返回的 promise 中的代碼應該連續運行,並且在循環之后,代碼應該只在數組內的所有承諾都得到解決時才繼續運行(因此我使用Promise.all() )。

對我來說很直觀的版本:

 const returnPromisesAsyncAwait = async () => { let pArray = [] for (let i = 1; i <= 5; i++) { pArray.push( // Is this antipattern? new Promise(async (resolve, reject) => { console.log('Entered promise' + i) await new Promise((res) => setTimeout(res, i * 100)) console.log('Finished promise 1 inside promise' + i) await new Promise((res) => setTimeout(res, i * 500)) console.log('Finished promise 2 inside promise' + i) resolve(true) }) ) } await Promise.all(pArray) console.log(pArray) console.log('Done!') } returnPromisesAsyncAwait()

此代碼返回的 output 與第二個代碼完全相同,后者應該是模式正確的:

 const returnPromisesThen = async () => { let pArray = [] for (let i = 1; i <= 5; i++) { pArray.push( // Is this antipattern? new Promise((resolve, reject) => { console.log('Entered promise' + i) new Promise((res) => setTimeout(res, i * 100)).then(() => { console.log('Finished promise 1 inside promise ' + i) new Promise((res) => setTimeout(res, i * 500)).then(() => { console.log('Finished promise 2 inside promise ' + i) resolve(true) }) }) }) ) } await Promise.all(pArray) console.log(pArray) console.log('Done!') } returnPromisesThen()

在這種情況下,有什么理由讓人們寧願使用 .then() 語法而不是 async/await 語法?

在您的示例中,兩個代碼都將導致相同的行為。 所以使用 async/await 很好。

循環內的風險是頂級等待; 例如

for (let i = 1; i <= 5; i++) {
    await fetch();
}

這樣做會暫停循環,直到每個 promise 解決。 這將導致性能問題,因為所有承諾都會以串行方式解決。 這通常是一種糟糕的模式,因為它破壞了異步調用的目的。

如果您只在 promise 回調中使用 async/await,那就沒問題了。

另一個類似的常見問題是等待多個呼叫彼此相鄰而不是使用Promise.all()

- const a = await fetchA();
- const b = await fetchB(); // Here fetchB doesn't start until fetchA complete.

+ const [a, b] = Promise.all([
+     fetchA(),
+     fetchB(),
+ ]);

我通過將循環內的代碼放入外部異步 function 解決了“問題”,所以我不會遇到將異步 function 添加到新 ZB321DE3BDC299EC807E9F795D7D9DEEB.

 asyncProcess = async (i) => { console.log('Entered promise' + i) await new Promise((res) => setTimeout(res, i * 100)) console.log('Finished promise 1 inside promise' + i) await new Promise((res) => setTimeout(res, i * 500)) console.log('Finished promise 2 inside promise' + i) } const returnPromiseWithExternalProcess = async () => { let pArray = [] for (let i = 1; i <= 5; i++) { pArray.push(asyncProcess(i)) } await Promise.all(pArray) console.log(pArray) console.log('Done!') } returnPromiseWithExternalProcess()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM