簡體   English   中英

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

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

我對此感到非常困惑,我想做的是,當 Express 從用戶那里接收數據時,我需要遍歷(訂單)並使用 Socket.IO 從另一台服務器請求每個(訂單)的一些數據然后等待數據,然后重新開始。

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

預期行為:訂單 ID:,訂單詳細信息:,流程已完成,

我得到的是:訂單 ID:,已完成流程,訂單詳情:,

我試過for loop & for await of . 但同樣的結果。

我想這就是你想要達到的目標


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 時執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM