【发布时间】:2021-06-08 22:37:42
【问题描述】:
构建 NodeJS REST API。 尝试从 FireBase 集合发送负载数据,然后将其发送给用户(作为 API 响应)。 看起来问题在于它不是等待firebase fetch解决,而是在没有收集数据的情况下发回响应。 (尝试使用 ASYNC-AWAIT 但它不起作用)
exports.getChatMessages = async (req, res, next) => {
const chatId = req.params.chatId
const getChatData = () => {
db
.collection('chats')
.doc(chatId)
.collection('messages')
.orderBy('timeStamp', 'asc')
.onSnapshot((snapshot) => {
snapshot.docs.forEach(msg => {
console.log(msg.data().messageContent)
return {
authorID: msg.data().authorID,
messageContent: msg.data().messageContent,
timeStamp: msg.data().timeStamp,
}
})
})
}
try {
const chatData = await getChatData()
console.log(chatData)
res.status(200).json({
message: 'Chat Has Found',
chatData: chatData
})
} catch (err) {
if (!err.statusCode) {
err.statusCode(500)
}
next(err)
}
}
如您所见,我使用了 2 个 console.logs 来了解问题所在,终端日志如下所示:
- [](来自 console.logs(chatData))
- 所有消息(来自 console.log(msg.data().messageContent))
有什么方法可以在真正获取firebase数据之前阻止代码?
【问题讨论】:
标签: node.js firebase google-cloud-firestore async-await synchronization