Javascript异步函数流程

2023-09-03前端开发问题
2

本文介绍了Javascript异步函数流程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如果有空位,我的职能部门应该分配一名员工.我不明白为什么即使我使用了等待",程序也不能同步.

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".

在函数的第一行,程序按预期运行.它等待从数据库中获取席位",然后执行if(seats.length > 0)"检查并初始化一个空数组.

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

我的问题在第 13 行代码,在await seat.forEach(async function(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.

只有在遍历所有席位并填充员工数组后,我才想继续执行employees.forEach(employee => {"行.

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

相反,调用之后会发生什么
-----"var employee = await connection.EmployeesGraph.findAll({ "---- ,程序不等待sequelize从数据库中获取员工然后去----"employees.push(employee);"---- ,如预期的那样.
它转到 ----"employees.push(employee);"---- 之后的行上的括号,然后我收到错误 "TypeError: Cannot read property 'catch' of undefined".

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?

推荐答案

最简单的解决方案是为此任务使用实际的 for 循环而不是 forEach.forEach() 不会等待迭代所有内容.

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

这篇关于Javascript异步函数流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

Fatal error: Call to a member function fetch_assoc() on a no
业务场景:使用update语句去更新数据库字段。 原因:update接收值不正确。原来代码: $query = "UPDATE student SET date = now() WHERE id = $id";$result = $mysqli-query($query2) or die($mysqli-error); // 问题出现了在这句 $data = $result-fetch_ass...
2024-12-13 前端开发问题
136

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

layui 单选框、复选框、下拉菜单不显示问题如何解决?
1. 如果是ajax嵌套了 页面, 请确保 只有最外层的页面引入了layui.css 和 layui.js ,内层页面 切记不要再次引入 2. 具体代码如下 layui.use(['form', 'upload'], function(){ var form = layui.form; form.render(); // 加入这一句});...
2024-11-09 前端开发问题
313

layui树状组件tree怎么默认勾选?
在layui树状组件tree中,勾选问题可以通过以下方法解决: 通过tree的oncheck事件来监听勾选操作,然后根据勾选状态进行相应的处理。例如: tree.on('check', function(obj) { // 获取勾选状态 var isChecked = obj.checked; // 获取当前节点数据 var data =...
2024-11-09 前端开发问题
372

layui laydate日期时间范围,时间默认设定为23:59:59
在Layui中,如果你想设置日期时间选择器(datetime)的默认结束时间为当天的23:59:59,你可以使用如下代码: laydate.render({ elem: '#test10' ,type: 'datetime' ,range: true ,max: '{:date("Y-m-d 23:59:59")}' ,ready: function(date){ $(".layui-laydat...
2024-10-24 前端开发问题
279

layui中表单会自动刷新的问题
layui中表单会自动刷新的问题,因为用到layui的表单,遇到了刷新的问题所以记录一下: script layui.use(['jquery','form','layer'], function(){ var $ = layui.jquery, layer=layui.layer, form = layui.form; form.on('submit(tijiao)', function(data){ a...
2024-10-23 前端开发问题
262