我有這個用 Typescript 撰寫的異步方法來查詢,使用 nodejs 驅動程式,一個 MongoDB;編譯器指示“myConnectedClient”之前的“await”對該運算式的型別沒有影響;我很困惑:對aggregate() 的呼叫是異步的嗎?所以,我必須等待,還是不?
謝謝。
async findQuery<T>(
collection: string,
findParams: Query<T>,
sort: Sort<T>,
myConnectedClient: MongoClient
) {
const firstResult = await myConnectedClient // the compiler indicates await is useless
.db("ZZZ_TEST_ALL")
.collection("my_collection_01")
.aggregate<string>([{ $project: { _id: 0, name: 1 } }]);
firstResult.forEach((field) => {
console.log(`Field: ${field}`);
});
}
更新:我必須在 .aggregate() 呼叫之后添加 .toArray() ;但為什么?誰能給我解釋一下機制?聚合()沒有回呼并且不回傳承諾?.toArray() 有替代品嗎?謝謝。
// now await it's ok
const firstResult = await myConnectedClient
.db("ZZZ_TEST_ALL")
.collection("my_collection_01")
.aggregate<string>([{ $project: { _id: 0, name: 1 } }]).toArray();
uj5u.com熱心網友回復:
Aggregate是同步的并回傳一個AggregationCursor。
游標有許多異步方法來檢索實際資料:toArray、forEach或簡單的迭代器
在第一個片段中 firstResult 是游標,因此無需等待。您使用 firstResult.forEach 來記錄結果。它確實回傳了承諾,但你忽略了它,這會咬你 - findQuery 回傳的承諾將立即得到解決,而 forEach 將并行迭代結果。為了保持承諾鏈,你應該做
const firstResult = myConnectedClient.......;
return firstResult.forEach(......);
所以findQuery只有當 forEach 被解決時,才會解決從 the 回傳的承諾,例如你完成迭代結果。
在第二個“更新”片段中,firstResult 是資料,因此您需要 await 從 toArray() 獲取它。顯式游標的等效項是:
const cursor = myConnectedClient.......;
const firstResult = await cursor.toArray();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/383523.html
標籤:javascript 打字稿 MongoDB
