這個問題在這里已經有了答案: 等待里面有一個承諾的 forEach 完成 (2 個回答) 在 forEach 回圈中使用 async/await (29 個回答) 昨天關閉。
我想從我的 mongodb 集合中檢索一個陣列,并在將它發送回客戶端之前,使用它。我想要的結果如下:
- 從 collection_A 獲取陣列
- 通過另一個 mongodb 查詢,用我剛得到的陣列做所需的作業
- 將陣列傳回客戶端
我當前的代碼如下所示:
db.collection("collection")
.find()
.toArray()
.then((arr) => {
arr.forEach(cur => {
db.collection("another-collection")
.count({key: cur.prop})
.then((retrieved) => {
cur.prop = retrieved; //The amount of count one live above
//This part runs later than the res.success below
})
.catch((err: any) => {
//Handle error
});
});
return arr;
})
.then(arr => {
res.success(arr);
})
.catch((err) => {
//Handle error
});
目前,我想要對檢索到的陣列進行的作業發生在 之后res.success(),因此在客戶端上我將獲取原始陣列。為什么呢?
uj5u.com熱心網友回復:
您可以Promise.all與Array#map.
.then((arr) =>
Promise.all(arr.map(cur =>
db.collection("another-collection")
.count({
key: cur.prop
})
.then((retrieved) => {
cur.prop = retrieved;
return curr;
})
.catch((err: any) => {
//Handle error
})
))
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/371144.html
標籤:javascript MongoDB 承诺
