简体   繁体   English

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

[英]what is the proper way to use nested async await in Javascript?

I'm really confused about this, what I'm trying to do is that when Express receives data from the user, I need to iterate over the (orders) and request some data for each (order) from another server using Socket.IO then waiting for the data, and do it all over again.我对此感到非常困惑,我想做的是,当 Express 从用户那里接收数据时,我需要遍历(订单)并使用 Socket.IO 从另一台服务器请求每个(订单)的一些数据然后等待数据,然后重新开始。

My Controller:我的 Controller:

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

Expected Behavior: Order ID:, order details:, Process Finished,预期行为:订单 ID:,订单详细信息:,流程已完成,

What I'm getting: Order ID:, Process Finished, order details:,我得到的是:订单 ID:,已完成流程,订单详情:,

I have tried for loop & for await of .我试过for loop & for await of . But the same result.但同样的结果。

I suppose that's what you're trying to achieve我想这就是你想要达到的目标


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

You dont need to create an event listener for each order, that listener will be executed always when the event name requestOrderDetails is emitted.您不需要为每个订单创建一个事件侦听器,该侦听器将始终在发出事件名称 requestOrderDetails 时执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM