I have a for each loop where I check something inside of it. This check is asynchronous and when this check is false, I want to break the loop. Here is my code:
addReservation(reservation: Reservation) {
this.deskService.loadDesksWhereRangeGreater(reservation.persons).subscribe(
desks => {
if (desks.length > 0) {
for (const desk1 of desks) {
console.log('checking');
if (this.checkForAvailability(desk1, reservation)) {
console.log('found');
}
}
}
}
);
}
async checkForAvailability(desk: Desk, reservation: Reservation) {
await this.db.collection('Desks').doc(desk.id)
.collection('Reservations', ref => ref.where('timestamp', '<=', reservation.timestamp + this.reservationDelta)
.where('timestamp', '>', reservation.timestamp - this.reservationDelta))
.valueChanges().subscribe(reservations => {
if (reservations.length === 0) {
console.log('reservation possible for ' + desk.nr);
return true;
} else {
console.log(desk.nr + ' Belegt');
return false;
}
});
}
However the await
part isn't really working. It just iterates through the loop without waiting for the asynchronous function each iteration.