user3378165 user3378165 - 3 months ago 21
Ajax Question

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 promise as I saw that
async=false
is deprecated.

self.getBalance = function (order) {
var balance;
$.ajax({
url: "/API/balance/" + order,
type: "GET",
async: false,
success: function (data) {
balance = data;
},
done: function (date) {
}
});
return balance;
}


Would you be able to help me? I just need an example to understand it.

Answer

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
});