forEach with Firebase call



我正试图通过比较预订网站中培训师时间表中与其他预订(从数据库中单独调用(的冲突来验证预订。

我知道Firebase调用是异步的,因此我需要找到一种方法来等待forEach函数中的所有预订被提取和验证。

我试着在forEach之前放置一个标志变量,并在它的末尾记录它,但显然它不起作用,因为console.log不会等待forEach完成后再运行。

我读过关于"异步等待"的文章,但对于这种情况来说,它似乎太致命了(?(。能有更简单的方法吗?

感谢您的帮助。

const bookingData = {
coursename:this.state.coursename,
location:this.state.location,
trainerid:this.state.trainerid,
startDatetime: this.state.startDatetime,
endDatetime: this.state.endDatetime,
} //FORM DATA I WANT TO VALIDATE

db.collection('timetables').doc(timetableid).get().then(timetable=>{
const data = timetable.data(); //ARRAY OF BOOKING ID'S
data.bookings.forEach(bookingid=>{
db.collection('bookings').doc(bookingid).get().then(bookingref=>{
//FOR EACH 'BOOKING' DOCUMENT IN MY DB, I WANT TO PERFORM THE FOLLOWING OPERATION
const booking = bookingref.data().bookingInfo;
if( booking.startDatetime.toDate() <= bookingData.startDatetime &&
booking.endDatetime.toDate() >= bookingData.startDatetime &&
booking.startDatetime.toDate() <= bookingData.endDatetime &&
booking.endDatetime.toDate() >= bookingData.endDatetime) {
console.log('TIME SLOT UNAVAILABLE')                             
}
else {
console.log('TIME SLOT AVAILABLE')                              
}
}).catch(err=>console.log(err));
});
})
// FIND A WAY TO SEE IF THE BOOKING WAS VALID AFTER BEING COMPARED WITH ALL OF THE BOOKINGS IN THE DB
  1. forEach更改为map
  2. 返回映射中db调用产生的promise
  3. 在控制台日志所在的位置返回一个布尔值。让我们说真实意味着可用
  4. 现在map的结果将是一个promise数组,解析为所有布尔值
  5. Promise.all等待所有这些承诺
  6. 然后放一个then。它将接收布尔值数组
  7. 如果所有这些都是真的,那么时隙是可用的

代码:

Promise.all(
data.bookings.map(
booking => db....get().then(bookingRef => {
// return true or false based on your condition
})
)
).then(results => {
// this will wait for all the db calls to complete.
// and you get all the booleans in the results array.
const isAvailable = !results.includes(false);
});

最新更新