【发布时间】:2018-11-07 16:34:55
【问题描述】:
我已经开始学习 NodeJS 以将其与 Firebase 一起使用以创建函数。
我目前卡住了,因为我嵌套了必须是异步的 forEach。
我会尽量让大家理解。
我有 3 个节点:
- 终端
- 预订
- TerminalBookings(类似于连接表)
我必须创建一个函数来关联所有终端及其预订。
所以我必须获取所有终端,对于每个终端,我可以获得所有关联的终端预订(节点键是终端 ID,所有值都是预订 ID)。
然后当我有所有的终端预订时,我可以在预订节点中获取预订信息。
使用 Sql 看起来很容易,但我可以弄清楚如何使用 NodeJS 来做到这一点。
这是我所拥有的(在这种状态下,无法工作,但看起来像我想做的那样):
async function getReservationsSnapshotByTerminalId(terminalId) {
const terminalReservationsSnap = await admin.database().ref(`/terminalBookings/${terminalId}`).once('value');
const terminalReservations = Object.keys(terminalReservationsSnap.val());
const reservationsSnapshot = terminalReservations.map((reservationId) => {
return admin.database().ref(`/bookings/${reservationId}`).once('value');
});
return Promise.all(reservationsSnapshot);
}
exports.showTerminalsWithReservations = functions.https.onRequest(async (request, response) => {
let terminals = [];
try {
const terminalsSnapshot = await admin.database().ref('/terminals/').once('value');
terminalsSnapshot.forEach(terminalSnapshot => {
const terminal = new Borne(terminalSnapshot.key, terminalSnapshot.val());
const bookingsSnapshot = await getReservationsSnapshotByTerminalId(terminal.key);
bookingsSnapshot.forEach(booking => {
terminal.bookings.push(booking.val());
});
terminals.push(terminal);
});
} catch(error) {
}
});
但是因为这条线它不能工作:
const bookingsSnapshot = await getReservationsSnapshotByTerminalId(terminal.key);
如果我想使用 await,父 forEach 必须异步,但这是不可能的。
我认为我处理此功能的方式不正确,但我被卡住了,我不知道该怎么做。
如果我错了,请随时完全重建此功能。
【问题讨论】:
标签: node.js firebase asynchronous firebase-realtime-database async-await