How To Replace 'async=false' With Promise In Javascript?
I have read a lot about promises but I'm still not sure how to implement it. I wrote the folowing AJAX call with async=false in order for it to work, but I want to replace it with
Solution 1:
Return promise object from getBalance
method:
self.getBalance = function(orderNumber) {
return $.ajax({
url: "/Exchange.API/accountInfo/balance/" + orderNumber,
type: "GET"
});
}
and use it later like this:
service.getBalance().then(function(balance) {
// use balance here
});
Solution 2:
As first point, you don't want to set an asynchronous call to false as it will lock the UI.
You could simplify your method returning the ajax object and the handle it as a promise.
self.getBalance = function(orderNumber) {
return $.ajax({
url: "/Exchange.API/accountInfo/balance/" + orderNumber,
type: "GET",
});
};
var demoNumber = 12;
self.getBalance(demoNumber).then(function(data){
console.log(data);
},function(err){
console.log("An error ocurred");
console.log(err);
});
Post a Comment for "How To Replace 'async=false' With Promise In Javascript?"