[英]How to iterate Set of promises? (async)
我有一組承諾:
const testQueue = new Set()
const promise1 = new Promise(resolve => resolve(1))
const promise2 = new Promise(resolve => resolve(1))
testQueue.add(promise1)
testQueue.add(promise2)
testQueue.forEach((promise) => {
console.log(`[promise]:`, promise)
})
如您所知,forEach 將給我每個 promise,但如果我嘗試觸發它並等待解決或拒絕,它不會等待並跳轉到集合中的下一個項目。
如果我們將 promise 存儲在一個數組中,我們可以這樣做:
const promises = [p1, p2]
for (const promise of promises) {
await promise // it will wait between promises
// of course, inside async function
}
是否可以迭代異步集合的承諾?
此問題也可以匹配 Map 集合。
Promise.all
將您的 Promises 集轉換為數組。 然后使用Promise.all
例如:
await Promise.all([...testQueue])
[... setVariable]
做什么 “...”展開集合的元素,就像它對數組所做的那樣。 [
和]
然后將結果重新組合到一個數組中。
因此,如果您有一個集合s
,您可以使用[...s]
將其轉換為一個數組。
感謝@VLAZ 在評論中指出您可以這樣做:
await Promise.all(testQueue)
集合只是數據結構。 您指的是 “set of promises” 嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.