Javascript async function flow

吃可爱长大的小学妹 提交于 2019-12-20 06:29:09

问题


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


来源:https://stackoverflow.com/questions/56586037/javascript-async-function-flow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!