Nodejs在完成先前的逻辑时如何做一些逻辑

时间:2016-09-07 16:31:51

标签: node.js synchronous

数组[1,2,3,4]占用其中的2个,并发送2个请求;

完成后再取2并创建两个新请求;

我知道我不能像下面那样做,因为Nodejs是同步的;

var request = require('request');
var args=[1,2,3,4];
function chunk(){...}
args = chunk(args,2);   //My custom function to split array into chunks

args.forEach(function(value)
{
    value.forEach(function(value_value)
    {
       /***********sent requests**************/
        var options = {
            method: 'POST',
            url: 'http://dev.site/date.php',
            formData: {arguments:value_value}
        };
        request(options, function (error, response, body)
        {
            if (body=='hello') {
                console.log(body);
            }
        });
      /**************************************/
    });
});

请帮帮我

1 个答案:

答案 0 :(得分:0)

您可以使用request-promiseq - 然后使用链式响应:

var request = require('request-promise');
var Q = require('q');
var args=[1,2,3,4];

function chunk(){...}
args = chunk(args,2);   //My custom function to split array into chunks

args.forEach(function(value)
{
     var result = Q();
     args.forEach(function (t) {
        result = result.then(request_each.bind(null, value));
     });
     return result;  // result has the final promise (use .then on that)
});

function request_each(value) {
    return Q.all(value.forEach(function(value_value)
    {
       /***********sent requests**************/
        var options = {
            method: 'POST',
            url: 'http://dev.site/date.php',
            formData: {arguments:value_value}
        };

        return request(options);           
      /**************************************/
    }));
 }

您可以使用qrequest(更改request_each功能):

function request_each(value) {
    return Q.all(value.forEach(function(value_value)
    {
       var deferred = Q.defer();
       /***********sent requests**************/
        var options = {
            method: 'POST',
            url: 'http://dev.site/date.php',
            formData: {arguments:value_value}
        };

        request(options, function (error, response, body) {
            if (body=='hello') {
                deferred.resolve(body);
            }
        });
        return deferred.promise;           
      /**************************************/
    }));
 }