簡體   English   中英

使用 Promise.all 和 map function 按順序運行承諾

[英]Run promises sequentially with Promise.all and a map function

我一直在嘗試使用批處理數組並依次使用Promise.all和 map function 觸發請求:

 const slowAsync = (i) => { return setTimeout(() => { return Promise.resolve(i); }, 1000) } const batchedIds = [[1,2], [3,4], [5,6]]; batchedIds.map(async batch => { const response = await Promise.all(batch.map(id => { return slowAsync(id); })); console.log(response); })

現在控制台一次記錄所有內容

//after 1 second
[1, 2]
[3, 4]
[5, 6]

但我希望它以 1 秒的差異記錄 promise 的每個解析

//after 1 second
[1, 2]
//after 1 second
[3, 4]
//after 1 second
[5, 6]

是否可以在沒有遞歸或庫的情況下使用 map function 來做到這一點?

您的slowAsync function 未正確實現。 setTimeout回調中返回某些內容無效。 setTimeout本身返回一個數字標識符,而不是 promise。

其次,您應該用for循環替換您的.map()迭代,並將所有內容包裝在async function 中,以便您可以使用await

這是更正:

 const slowAsync = (i) => new Promise(resolve => setTimeout(() => resolve(i), 1000) ); const batchedIds = [[1,2], [3,4], [5,6]]; (async () => { for (const batch of batchedIds) { const response = await Promise.all(batch.map(id => { return slowAsync(id); })); console.log(response); } })();

除了 function 閉包,您還可以使用Function.prototype.bind()將批處理的各個id綁定到setTimeout()回調函數,如下所示:

 const batchedIds = [[1,2], [3,4], [5,6],[7,8,9,10]]; (async () => { for (const batch of batchedIds) { console.log(await Promise.all(batch.map(id=>new Promise(r=>setTimeout(r.bind(null,id),1000))))); } })();

暫無
暫無

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

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