在 Javascript 中使用嵌套异步等待的正确方法是什么?

时间:2021-03-03 19:54:15

标签: javascript node.js sockets asynchronous async-await

我对此真的很困惑,我想要做的是,当 Express 从用户接收数据时,我需要遍历(订单)并使用来自另一台服务器的每个(订单)请求一些数据然后Socket.IO等待数据,从头再来。

我的控制器:

exports.placeOrders = async (socket, orders) => {
    for await (order of orders){ 
        console.log("Order ID: " + order.id);   

        socket.emit('requestOrderDetails', order.id);

         await socket.on('getDetails' , async (response) => {

                 console.log("order details:" + response);

                //another processes that should be executed in order
                // await .. 
                // await ..


             })

        }
    console.log("Process Finished);
}
    

预期行为: 订单编号:, 订单详细信息:, 流程完成,

我得到了什么: 订单编号:, 工艺完成, 订单详情:,

我尝试了 for 循环和 for await 。但同样的结果。

1 个答案:

答案 0 :(得分:0)

我想这就是你想要达到的


exports.placeOrders = async (socket, orders) => {
  socket.on('requestOrderDetails' , async (response) => {

      console.log("order details:" + response);

      //another processes that should be executed in order
      // await .. 
      // await ..
  });

  for (let index = 0; index < orders.length; index++){ 
      console.log("Order ID: " + orders[index].id);   

      socket.emit('requestOrderDetails', orders[index].id);
  }
  
  console.log("Process Finished);
}

您不需要为每个订单创建一个事件监听器,当发出事件名称 requestOrderDetails 时,该监听器将始终被执行。