如何在javascript中用promise替换'Async=false'?



我已经读了很多关于promises,但我仍然不确定如何实现它。

我用async=false写了下面的AJAX调用,为了让它工作,但我想用承诺代替它,因为我看到async=false是不赞成的。

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

你能帮我吗?我只需要一个例子来理解它。

作为第一点,您不希望将异步调用设置为false,因为它将锁定UI。

你可以简化你的方法返回ajax对象和句柄作为一个承诺。

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

getBalance方法返回承诺对象:

self.getBalance = function (orderNumber) {
    return $.ajax({
        url: "/Exchange.API/accountInfo/balance/" + orderNumber,
        type: "GET"
    });
}

,然后像这样使用:

service.getBalance().then(function(balance) {
    // use balance here
});

最新更新