gpt4 book ai didi

Node.js 并行调用同一子休息服务并聚合响应

转载 作者:太空宇宙 更新时间:2023-11-03 22:12:16 26 4
gpt4 key购买 nike

我想从家长休息服务调用 child 休息服务。调用子服务的次数取决于父休息服务的参数。一旦我使用不同的参数同时调用所有子服务实例。我想合并所有 child 服务实例的响应。我正在使用下面的代码片段。但我不想使用超时。它应该是超时或子服务的所有调用都结束时,以较小者为准。

    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);

最佳答案

你也可以使用 Promise。假设 service 调用返回 Promise,然后您等待 all其中的一些都已实现。 Node.js 支持从 v4 开始的 Promise 。如果您有早期版本的 Node ,只需使用一些 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);
});

关于Node.js 并行调用同一子休息服务并聚合响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38828184/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com