Reputation: 489
I'm using Angular 1.6.3
I need to make 3 get requests and finally check if at least one gives success response. Right now I have written this code:
var result = new Array();
$http.get("link1",
{
"params": {
"email": user.email,
}
}).then(function (successResult) {
result[0] = false;
}, function (errorResult) {
result[0] = true;
});
$http.get("link2",
{
"params": {
"email": user.email,
}
}).then(function (successResult) {
result[1] = false;
}, function (errorResult) {
result[1] = true;
});
$http.get("link3",
{
"params": {
"email": user.email,
}
}).then(function (successResult) {
result[2] = false;
}, function (errorResult) {
result[2] = true;
});
if(result[0] || result[1] || result[2]){
error();
}
But sometimes one of GET
requests returns -1
as Http status code when it should give 200
. I know that all $http
request are async and I think this is the main reason. What is the proper way to solve this issue?
Upvotes: 1
Views: 322
Reputation: 1200
Right way of doing this is to use $q.all
Use the following code.
var promise1 = $http.get("link1",
{
"params": {
"email": user.email,
}
});
var promise2 = $http.get("link2",
{
"params": {
"email": user.email,
}
});
var promise3 = $http.get("link3",
{
"params": {
"email": user.email,
}
});
$q.all([
promise1,
promise2,
promise3
]).then(function(data)
{
// data[0] contains the response of the promise1 call
// data[1] contains the promise2 response
// data[2] contains the promise3 response.
$scope.variable = data;
},
function(errorData){
});
Upvotes: 2
Reputation: 3187
Due to the asynchronous nature of HTTP requests, you're going to be much better off using promises correctly. I recommend Promise.all() which can check the status of the responses once they have all arrived.
Alternatively, you could use a function to check each response as they arrive (rather than waiting for all promises to resolve).
For example:
checkResponse(res) {
// logic here
}
$http.get('xxx').then(res => checkResponse(res))
$http.get('yyy').then(res => checkResponse(res))
$http.get('zzz').then(res => checkResponse(res))
Upvotes: 0
Reputation: 380
you can use like this
var result = new Array();
$http.get("link1",
{
"params": {
"email": user.email,
}
}).then(function (successResult) {
result[0] = false;
}, function (errorResult) {
result[0] = true;
}).then($http.get("link2",
{
"params": {
"email": user.email,
}
}).then(function (successResult) {
result[1] = false;
}, function (errorResult) {
result[1] = true;
})).then(
$http.get("link3",
{
"params": {
"email": user.email,
}
}).then(function (successResult) {
result[2] = false;
}, function (errorResult) {
result[2] = true;
}));
but here is a better way is to call with promise here is the link to the official site
https://docs.angularjs.org/api/ng/service/$http
Upvotes: 1