简体   繁体   中英

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.

My 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,

What I'm getting: Order ID:, Process Finished, order details:,

I have tried 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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