async for多个xmlhttprequests的每个问题

async forEach issue with multiple xmlhttprequests

本文关键字:问题 xmlhttprequests for 多个 async      更新时间:2023-09-26

我有一个关于nodejs中异步包的问题。

从本质上讲,我拥有的是一个对象数组,其中每个元素都包含我向远程服务器形成xmlhttprequest所需的信息。所以我想我可以使用async.forEach按顺序激发请求,将结果存储在一个变量中,然后在代码中使用它们。

以下是示例代码:

async.series([
  function(callback)
  {  //async.series element 1
      async.forEach(req_info_arr, function(req_info_element, callback) {
            var url = ... //form the url using the info from req_info_element
            var req = new XMLHttpRequest();
            req.open("GET", url, true);
            req.send();  //fires the request
            req.onload = function() {
              //do stuff
              callback();
            }//end of onload
            
            req.onerror = function() {
               //do stuff
                callback(err);
            }
    }/*end of async_forEach */, callback);
  callback();
  },
  function(callback){
    //async.series element 2
    //do stuff...want this to be done only after we have received a response for every request fired in async.series element 1
  }
  ], function(err) {
  });  

结果是:async.forEach遍历req_info_arr中的每个元素,激发每个元素的请求。

一旦完成。这到达了async.series中的第二个元素。但是我还没有收到async.sSeries元素1中激发的xhr的响应,所以我的代码失败了。

这个问题有解决办法吗?我误解什么了吗?

如有任何帮助/建议,我们将不胜感激。

我想是因为回调();在async.forEach的正下方,这会立即触发该系列的下一步:

.
.
.
}/*end of async_forEach */, callback);
callback(); //<-- remove this guy

这是因为您正在调用async.forEach()块之后的第一个async.series()回调。

您需要删除该回调();在第21行。