我正在嘗試做的事情:
我正在嘗試使用遞回方法從 firestore(firebase 資料庫)中檢索所有評論及其回復。這是資料的結構:

什么問題 父異步函式不等待嵌套異步函式完成。
getThread = async (req, res) => {
// Getting comments belonging to thread
const thread_document = await db.doc(`/Threads/${req.params.threadid}`).get()
threadData = thread_document.data()
threadData.threadid = thread_document.id
const comment_query = await db.collection('Comments').where('threadid', '==', threadData.threadid).get()
// Getting replies belonging to comments
for (document of comment_query){
let commentData = await getReplies(document.id)
threadData.comments.push(commentData )
}
return res.json(threadData)
}
//Recursive function to retrieve replies
getReplies = async (id) => {
let comment = await db.doc(`/Comments/${id}`).get()
let commentData = comment.data()
commentData.comment_replies = commentData.replies.map(idx => {
// The parent async function does not wait for the the async function here to finish.
// Placing a await keyword here will raise the error 'await is only valid in async functions and the top level bodies of modules'
return getReplies(idx)
})
console.log(commentData)
return commentData
}
給定下面的例子,
由于父異步函式不等待嵌套的異步函式,所以現在的執行順序是A -> B -> a,并且a無法映射到并且評論A的commentData最終為空。因此,我想編程做 A -> a -> B。為此,我想在 getReplies 之前放置一個 await 關鍵字,例如

commentData
return await getReplies(idx)
但它會引發錯誤,
await is only valid in async functions and the top level bodies of modules.
這令人困惑,因為getReplies它已經是一個異步函式。我已經研究了 stackoverflow 中的其他解決方案,但我無法讓遞回函式正常作業。任何見解將不勝感激,謝謝。
uj5u.com熱心網友回復:
commentData.comment_replies = commentData.replies.map(idx => {
// ...
return getReplies(idx)
})
這個 map 陳述句將創建一個 Promise 陣列,但不會等待這些 Promise 完成。您應該使用 Promise.all 將它們組合成一個 Promise,然后等待該 Promise 以獲取評論回復陣列:
const promises = commentData.replies.map(idx => {
return getReplies(idx);
});
commentData.comment_replies = await Promise.all(promises);
這令人困惑,因為 getReplies 已經是一個異步函式。
您收到該錯誤是因為您所在的函式是idx => { return getReplies(idx) },它不是異步函式。但是無論如何,在那里等待并不能解決您的問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/440237.html
標籤:javascript 节点.js 异步 谷歌云火库 异步等待
