NODE.JS-完成多个请求后如何正确调用next()? [英] NODE.JS - How to invoke correctly next() after multi REQUESTS are done?

查看:56
本文介绍了NODE.JS-完成多个请求后如何正确调用next()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用forEach()循环在ARRAY上运行.对于每个元素,我需要调用一个请求.我想在所有调用的请求完成后调用next()(假设我至少有100个请求要调用).

I am running over an ARRAY using forEach() loop. For every element , I need to invoke a request. I want to call the next() after ALL invoked requests are done (assume I have at least a 100 requests to invoke).

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

Any ideas how to approach this?

这里有一些示例代码来演示我的问题-

Here is a little sample code to demonstrate my question -

var arr = ["A" , "B", "C" , "D" , "E"];
arr.forEach(function (arrayItem) {
	var options = { 
        method: 'GET',
        url:"some_url",
        headers: {...} 
  };
  request(options, function (error, response, body)
  {
    if (error)  {next(error);}

    // DO_SOMETHING based on arrayItem

  }); // end of request()
});  //end of forEach

// WHERE should I place the next()?

推荐答案

有两种方法可以执行此操作.由于所有对 request()的调用都是异步的,因此将在循环完成后很长时间以后完成,因此您必须以某种方式对其进行跟踪.我将展示两种方法,一种使用Promises,一种使用计数器.

There are a couple ways you can do this. Since all the calls to request() are asynchronous and thus will finish sometime in the future long after your loop has finished, you will have to keep track of them somehow. I'll show two methods, one using Promises and one using a counter.

承诺

// create wrapper function that returns a promise
function requestPromise(options) {
    return new Promise(function(resolve, reject) {
        request(options, function(error, response, body) {
            if (error) return reject(error);
            resolve({response: response, body: body});
        });
    });
}

var arr = ["A" , "B", "C" , "D" , "E"];

Promise.all(arr.map(function(item) {
    // create options object here for each request
    var options = { 
        method: 'GET',
        url:"some_url",
        headers: {...} 
    };

    return requestPromise(options);

})).then(function(results) {
    // process results here

    // call next() here because all processing is now done
    next();
}).catch(function(err) {
    // error happened
    next(err);
});

手动计数器

var arr = ["A" , "B", "C" , "D" , "E"];
var errDone = false;
var cntr = 0;
arr.forEach(function (arrayItem) {
    var options = { 
        method: 'GET',
        url:"some_url",
        headers: {...} 
  };
  request(options, function (error, response, body) {
    if (error)  {
        if (!errDone) {
            // latch error so we don't call next(error) multiple times
            errDone = true;
            next(error);
        }
    } else {
        // process result here

        // check if this is the last response
        ++cntr;
        if (cntr === arr.length) {
            // all responses done here
            next();
        }
    }
  });

这篇关于NODE.JS-完成多个请求后如何正确调用next()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆