我想从父母休息服务中拨打儿童休息服务。调用子服务的次数取决于父服务的参数。一旦我用不同的参数同时调用所有子服务实例。我想结合所有子服务实例的响应。我正在使用下面的代码片段。但我不想使用超时。它应该是超时或者当所有的子服务调用都超过了它时。
for( i=0; i<length; i++)
{
url=accountID[i] +'+'+sortcode[i] +'+' +accountHolderName[i];
micro(url ,filter[i],function(resp)
{
this.resutlObject[count]=resp;
console.log("count"+count);
count=count+1;
}.bind( {resutlObject: resutlObject} ));
}//end of for
setTimeout(function () {
console.log("in time out");
res.end(JSON.stringify(resutlObject || {}, null, 2));
},500);
答案 0 :(得分:1)
你也可以使用Promises。假设service
调用返回promise,那么你等待它们all完成。 Node.js支持从v4开始的promise。如果您有早期版本的节点,只需使用一些library。
//Instead of
function micro(url, filter, cb) {
var resp = "result of async job";//do some async work
cb(resp)
}
//Modify your service to return a promise
function micro(url, filter) {
return new Promise(function(resolve, reject) {
var resp = "result of async job using `url` and `filter`";
if (resp) {
resolve(resp);
} else {
reject("reason");
}
});
}
//Create a list of service calls.
var promises = [];
for( i=0; i<length; i++)
{
url=accountID[i] +'+'+sortcode[i] +'+' +accountHolderName[i];
promises.push(micro(url, filter[i]));
}
//Wait for all off them to fulfill
Promise.all(promises)
.then(function(resultObject) {
//Response
res.end(JSON.stringify(resultObject || {}, null, 2));
}, function(reason) {
res.sendStatus(500);
console.error(reason);
});
答案 1 :(得分:0)
您可以使用async module。它旨在做你想要的东西。像这样:
var async = require('async');
var collection = [];
for(i=0;i<length;i++) {
collection.push(
(function(i) {
return function(callback) {
url=accountID[i] +'+'+sortcode[i] +'+' +accountHolderName[i];
micro(url ,filter[i],function(resp) {
callback(null, resp);
});
}
})(i)
);
}//end of for
async.parallel(collection, function(err, results) {
console.log(results) // array of results from all requests
})
会发生什么
async.parallel
将一系列函数作为参数。每个函数都接收callback
作为参数。回调是一个函数,它以error
和result
为参数。
执行所有回调后async
调用最终回调函数,该回调函数接收来自所有其他回调的结果数组。
在循环中,我们正在创建一个函数集合。在这个例子中,代码有点复杂,因为我们使用闭包来保留每个函数的i
值。
答案 2 :(得分:0)
您可以使用异步模块async。它提供了并行的foreach循环。
var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
var configs = {};
async.forEachOf(obj, function (value, key, callback) {
fs.readFile(__dirname + value, "utf8", function (err, data) {
if (err) return callback(err);
try {
configs[key] = JSON.parse(data);
} catch (e) {
return callback(e);
}
callback();
})
}, function (err) {
if (err) console.error(err.message);
// configs is now a map of JSON data
doSomethingWith(configs);
})
这里的示例是读取参数中列出的文件。 同样地,你可以为你的任务做点什么