最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ajax - How to replace 'Async=false' with promise in javascript? - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Aug 11, 2016 at 11:11 user3378165 asked Aug 11, 2016 at 11:07 user3378165user3378165 6,92618 gold badges66 silver badges108 bronze badges 1
  • May be you should try to structure your logic to avoid async=false behaviors, If you are learning promises you should try to load things with promises each time you need them, but you can decide to catch them or not inside the promise method. – fbiagi Commented Aug 11, 2016 at 11:17
Add a ment  | 

2 Answers 2

Reset to default 5

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

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
});
发布评论

评论列表(0)

  1. 暂无评论