Javascript async function flow

2020-05-06 12:20发布

问题:

My function should assign an employee on a seat if the seat is available. I do not understand why the program doesn't act as synchronous even though I used "await".

In the first lines of the function, the program acts as expected. it waits to get "seats"from the database, then performs the "if(seats.length > 0)" check and initialises an empty array.

async function AssignSeat(req, res) {

  var seats = await connection.SeatEmployees.findAll({
    where: {
      SeatId: req.body.seat.SeatId
    }
  })
  .catch(err => {
    res.status(err.status).json(err)
  });


  if(seats.length > 0){
    var isShared = true;

    var employees = [];

    await seats.forEach(async function(seat){
      var employee = await connection.EmployeesGraph.findAll({
        where: {
          id: seat.EmployeeGraphId
        }
      })
      .catch(err => {
        res.status(err.status).json(err)
      });

      employees.push(employee);
    })
    .catch(err => {
      res.status(err.status).json(err)
    });


    employees.forEach(employee => {
      if(employee.frequent == true)
          isShared = false;
    })


    if(isShared == true){
      //assign user to seat;
    }
  }
}

My problem is at the 13th line of code, at " await seats.forEach(async function(seat)".

What I want to do is go through each element of "seats", Get the employee assigned to that seat, and push it into the "employees" array.

Only after iterating from all the seats and filling the employees array, I want proceed with the "employees.forEach(employee => {" line.

Instead, what happens is that after calling
-----"var employee = await connection.EmployeesGraph.findAll({ "---- ,the program doesn't wait for sequelize to get the employee from the database and then go to ----"employees.push(employee);"---- , as intended.
It goes to the paranthesis on the line after ----"employees.push(employee);"---- , then I get the error "TypeError: Cannot read property 'catch' of undefined".

Could you please explain why this happens?

回答1:

The easiest solution is to use an actual for loop instead of forEach for this task. forEach() won't wait to iterate over everything.

try {
  for (const seat of seats) {
    var employee = await connection.EmployeesGraph.findAll({
        where: {
          id: seat.EmployeeGraphId
        }
      })
      .catch(err => {
        res.status(err.status).json(err)
      });

    employees.push(employee);
  }
} catch (err) {
  res.status(err.status).json(err)
}