如何实现异步循环(JS)

时间:2018-08-01 21:00:00

标签: javascript angular async-await

我为每个循环检查一个内部循环。此检查是异步的,当此检查为false时,我想中断循环。这是我的代码:

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;
        }
    });
}

但是await部分并没有真正起作用。它只是遍历循环,而不必等待每次迭代的异步功能。

2 个答案:

答案 0 :(得分:1)

您需要await的结果checkForAvailability

addReservation(reservation: Reservation) {
    this.deskService.loadDesksWhereRangeGreater(reservation.persons).subscribe(
        async desks => {
            if (desks.length > 0) {
                for (const desk of desks) {
                    const available = await this.checkForAvailability(desk, reservation)
                    if (!available) { break }
                }
            }
        }
    );
}

checkForAvailability(desk: Desk, reservation: Reservation) {
  // here, you need to return a promise
  return new Promise(resolve => {
    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 => {
      resolve(reservations.length === 0)
    });
  })
}

答案 1 :(得分:1)

您需要在checkForAvailability函数中返回承诺,并且addReservation函数必须异步才能使用{{1} }。

  

await运算符用于等待Promise。 只能在异步函数中使用。

在这里,示例如何实现异步循环

await