Reputation: 947
How do I do stuff after the ajax-call is done in with angular?
See this code:
$http({
method: 'GET',
url: myUrl + myData
}).
success(function (data) {
doStuff(data);
}).
error(function (data) {
doStuff(data);
});
alert("do not alert me before running doStuff()");
I want to run doStuff before the alert
Upvotes: 1
Views: 204
Reputation: 1297
You might want to use 'finally':
http({
method: 'GET',
url: myUrl + myData
}).
success(function (data) {
doStuff(data);
}).
error(function (data) {
doStuff(data);
}).
finally(function(data){
alert("do not alert me before running doStuff()");
});
However 'finally' is a reserved word in javascript and this will break on ie8, so a more compatible way to use it would be calling it with brackets notation like
http({
method: 'GET',
url: myUrl + myData
}).
success(function(data){
doStuff();
})
['finally'](function(data){
doOtherStuff();
});
// note that there is no dot before ['finally']
Check out the official documentation on Promises Api in angular to learn more: https://docs.angularjs.org/api/ng/service/$q
Upvotes: 1
Reputation: 1885
If doStuff is synchronous (blocking the next line until it returns):
$http({
method: 'GET',
url: myUrl + myData
}).
success(function (data) {
doStuff(data);
alert("do not alert me before running doStuff()");
}).
error(function (data) {
doStuff(data);
alert("do not alert me before running doStuff()");
});
If doStuff is asynchronous (next line is executed before the function returns) you need to use a callback:
function doStuff(data, callback) {
...do the stuff here...
callback(); // Run the callback
}
function myAlertFunc() {
alert("do not alert me before running doStuff()");
}
$http({
method: 'GET',
url: myUrl + myData
}).
success(function (data) {
doStuff(data, myAlertFunc);
}).
error(function (data) {
doStuff(data, myAlertFunc);
});
Upvotes: 1