[英]Calling APIs in a loop - Angular js
I have a set of APIs which I have to run inside a for loop 我有一组必须在for循环中运行的API
for(var i=0; i<array.length; i++ )
service.getfunction(array[i]).then(function(response) {
service.getfunction1(response).then(function(response) {
service.getfunction2(response).then(function(response) {
service.getfunction3(response).then(function(response) {
console.log(response);
});
});
});
});
)
Second loop should start only after I got result from last getfunction3 API for first loop. 仅当我从上一个循环的上一个getfunction3 API获得结果后,第二个循环才应开始。 How can I do this?
我怎样才能做到这一点?
First of all - you can chain your promises like: 首先-您可以像以下那样链接您的承诺:
function doJob(i) {
return service.getfunction(array[i]).then(function(response) {
return service.getfunction1(response);
}).then(function(response) {
return service.getfunction2(response);
}).then(function(response) {
return service.getfunction3(response);
}).then(function(response) {
console.log(response);
});
}
This function will return promise that will be resolved once all this service calls done. 此函数将返回将在所有这些服务调用完成后解决的promise。 And now lets use it:
现在让我们使用它:
var p = Promise.resolve(true);
for(var i = 0; i < array.length; i++) {
(function(idx) { //We need to wrap it or we will pass incorrect i into doJob
p = p.then(function() {
return doJob(idx);
});
})(i);
}
p.then(function() {
console.log('Everything done');
});
Wrap it in a function: 将其包装在一个函数中:
// Declare function
function LoopAPI() {
for(var i=0; i<array.length; i++ )
service.getfunction(array[i]).then(function(response) {
service.getfunction1(response).then(function(response) {
service.getfunction2(response).then(function(response) {
service.getfunction3(response).then(function(response) {
console.log(response);
// Call function again
LoopAPI();
});
});
});
});
)
}
// First call
LoopAPI();
You can chain promises then use Array.reduce to call them in order as such: 您可以链接promise,然后使用Array.reduce依次调用它们:
array.reduce(function(previous, next)
{
return previous.then(function()
{
return service.getfunction(next);
})
.then(function(response)
{
return service.getfunction1(response);
})
.then(function(response)
{
return service.getfunction2(response);
})
.then(function(response)
{
return service.getfunction3(response);
});
}, Promise.resolve())
.then(function()
{
console.log("All done.");
})
.catch(function(error)
{
console.log(error);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.