数组[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);
}
});
/**************************************/
});
});
请帮帮我
答案 0 :(得分:0)
您可以使用request-promise
和q
- 然后使用链式响应:
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);
/**************************************/
}));
}
您可以使用q
和request
(更改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;
/**************************************/
}));
}