I have to do 2 AJAX calls. Second one depends on the first call result. Right now I do it like this:
Service.getA(car).then(function(carInfo) {
if (carInfo.success) {
Service.getB(carInfo.number).then(function(holderInfo) {
console.log(holderInfo);
});
}
});
Service:
getA: function(car) {
return Server.execute({
method: 'GET',
url: 'a/a',
params: {
car: car
},
}).then(function (carInfo) {
return carInfo;
});
},
getB method is analogous - just another URL and another parameters. I am learning angular and want to implement this code using promises and defers (google suggest that code will be more beautoful). How can I do that?
The way you've done it is typically how you chain ajax calls though you can simplify this a bit:
Service.getA(car).then(function(carInfo) {
Service.getB(carInfo.number).then(function(holderInfo) {
console.log(holderInfo);
});
});
For errors have your server return Bad Request 400 and then you can chain the .error() callback instead of determining success based on the success property.
As Cerbrus pointed out, $q.all([promise1, promise2]) executes them in parallel instead of one depending on the other.
Your getA method should just return the promise itself like so:
getA: function(car) {
return Server.execute({
method: 'GET',
url: 'a/a',
params: {
car: car
},
});
}
If you really need to bind the extra callback from within the service you can do this:
getA: function(car) {
return Server.execute({
method: 'GET',
url: 'a/a',
params: {
car: car
},
}).then(function (carInfo) {
//do something?
}, function () {
//handle error?
});
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With