WIRN
WIRN

Reputation: 947

do stuff after ajax is complete with angular

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

Answers (2)

canerbalci
canerbalci

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

Adrian Schmidt
Adrian Schmidt

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

Related Questions