关于jquery ajax:jquery ajax-使用promises / deferred对象为同一ajax调用处理不同的回调吗?

jquery ajax - using promises/deferred objects to handle different callbacks for the same ajax-call?

因此请考虑以下情形:

我想在我的电子商务脚本中多次检查产品的库存情况。

我所做的是

1
2
3
4
5
6
7
8
9
10
11
12
var checkStock = function(id) {
$.ajax({
    type:"POST",
    dataType:'json',
    url:"class/updateCart.php",
    data: { productID: id, action: 'checkStock' }
}).done(function(data) {
    return parseInt(data.stock);
}).fail(function(data) {
    return 'AJAX FAILED';
});
}

所以现在我想像这样使用它:

1
2
3
if(checkStock(productID) == 0) {
    // do something (A)
}

这显然没有用,所以在我的研究中我遇到了这个问题:

jQuery:ajax调用成功后返回数据


使用promise的目的是允许您将回调与原始操作分开(通过返回promise),并链接多个异步操作。

您需要将代码移动到promise回调中:

1
2
3
4
5
6
checkStock(productId)
    .then(function(result) {
        if (result > 5) {
            ...
        }
    });

您可以在每次调用该函数时添加不同的Promise回调。