Reputation: 626
I have to methods, that return promises. And I want to make second method to be executed after first would get and manipulate data. This question has being asked several times, still cannot find a way to make it work. Here is my code:
self.getSpesialitet = function () {
console.log("Starting Spesialitet");
return $.get(options.getSpesialitetUrl, { 'recno': recno }, function (data) {
////Code
console.log("Success Spesialitet");
});
};
self.getVedtak = function () {
console.log("Starting Vedtak");
return $.get(options.getVedtakUrl, { 'recno': recno }, function (data) {
////Code
console.log("Success Vedtak");
});
};
$.when(self.getSpesialitet()).then(self.getVedtak()).then(console.log("Everything is done"));
And here is the result witch I get:
Starting Vedtak
Starting Spesialitet
Everything is done
Success Vedtak
Success Spesialitet
And the result I would like to get:
Starting Vedtak
Success Vedtak
Starting Spesialitet
Success Spesialitet
Everything is done
Upvotes: 1
Views: 184
Reputation: 12295
You can use success
calls in order to chain your functions, like this:
self.getVedtak().success(function(){
self.getSpesialitet().success(function(){
console.log('Everything is done');
})
})
Upvotes: 1
Reputation: 1254
Please understand that $.get
, $.post
and $.ajax
calls are always asynchronous calls. It's like fire and forget. It doesn't wait until the execution is complete. To make your code work, you need to call your second method when the first method has returned.
Upvotes: 0