简体   繁体   English

如何在node.js中获得多个异步http请求及其回调的串行流控制?

[英]How to get serial flow control of multiple asynchronous http requests and their callbacks in node.js?

I have tried this many ways (queue, with/without async module, handler, etc.), but I cannot figure out how to apply serial flow control to an asynchronous http request and its callback. 我已经尝试了很多方法(队列,有/没有异步模块,处理程序等),但我无法弄清楚如何将串行流控制应用于异步http请求及其回调。 I have an array of urls I want to use to make http requests with and insert individual documents within each response into a mongo db collection. 我有一系列网址,我想用来发出http请求,并在每个响应中插入单个文档到mongo db集合中。 Once the inserts are finished I want to proceed to the next http request. 插入完成后,我想继续下一个http请求。 Here is where I am at, but this still kicks off all the http requests before the inserts happen. 这是我所处的位置,但这仍然会在插入发生之前启动所有http请求。

var request = require('request');
var async = require('async');

var urls = ['http://getsomejson/1', 'http://getsomejson/2', 'http://getsomejson/3'];

async.forEachSeries(urls, function(url, callback) {
    // All of these requests are firing before http request callback logic is executed
    request(url, function (error, response, body) {
        async.forEachSeries(body.docs, function(doc, callback) {
            // Do the inserts for this response
            callback();
        }, function(err) {
            // handle errors
        });
    })
    callback();
}, function(err) {
    // handle errors
});

Any suggestions would be greatly appreciated. 任何建议将不胜感激。

The callback passed to the function(url, callback) function is what triggers the next element in the series. callback传递给function(url, callback)的功能是什么触发该系列中的下一个元素。 If you just call it at the end like that, it is doing a loop just like if you did a for loop. 如果你只是在最后调用它,它就像你做一个for循环一样循环。 You should call that callback in the completion function of the request. 您应该在请求的完成函数中调用该回调。 That way it will jump to the next item after the request is done. 这样,它将在请求完成后跳转到下一个项目。

async.forEachSeries(urls, function(url, callback) {
  // All of these requests are firing before http request callback logic is executed
  request(url, function (error, response, body) {

    async.forEachSeries(body.docs, function(doc, callback) {
      // Do the inserts for this response
      callback();
    }, function(err) {
      // handle errors

      callback();
    });
  })
}, function(err) {
  // handle errors
});

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

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