javascript - 在jquery中获取多个延迟对象的响应

标签 javascript jquery ajax promise jquery-deferred

下面是我的带有 promise 的多个 ajax 调用。

$(window).load(function(){
 $.when(getApiModemList()).done(function(vendors){

    var deferreds = calculateApiBalances(vendors);

    $.when.apply($,deferreds).done(function(balance) {
     console.log(balance);
     console.log("All Done");
    });

});


function getApiModemList(){
   return $.getJSON("url");
}

 function calculateApiBalances(vendors)
  {
   var defer=[];
   $.each(vendors,function(k,v){
    defer.push($.getJSON(someurl));
   });
  return defer;
 }

 });

函数calculateApiBalances()返回一些余额,我需要将其求和以获得所有余额的总计。 但是当打印 console.log(balance) 时,它没有为我提供有效的余额 json 数组。 另一个问题是,如果calculateApiBalances() 中的任何一个ajax 调用失败,它都不会打印“All Done”。 在上面的代码中应该做什么来实现这一点。

最佳答案

But when print console.log(balance) it doesnot provide me with valid array of balance json.

这是 $.when 的一个奇怪的事情。它不为您提供数组,而是使用多个参数调用回调。

Another issue is if any one of my ajax calls in calculateApiBalances() fails it doesnot prints All Done.

是的,因为当一个 Promise 失败时,整个 $.when() Promise 会立即被拒绝,并且您没有任何错误处理程序。如果您希望始终获得一个数组(可能包含无效响应),则必须单独捕获错误。另请参阅$.Deferred: How to detect when every promise has been executed .

What should be done in above code to achieve this.

首先,avoid the deferred antipattern :-)

$(window).load(function() {
    getApiModemList().then(calculateApiBalances).then(function() {
        var balance = Array.prototype.slice.call(arguments);
        console.log(balance);
        console.log("All Done");
    });
});


function getApiModemList() {
    return $.getJSON(somurl).then(function(res) {
        return res.data;
    });
}

function calculateApiBalances(vendors) {
    return $.when.apply($, $.map(vendors, function(v, k) {
        return $.getJSON(someurl).then(null, $.when);
    }));
}

Roamer 编辑:

这是主例程的一个版本,具有求和余额的机制。

    getApiModemList().then(calculateApiBalances).then(function() {
        var sumOfBalances = Array.prototype.reduce.call(arguments, function(tot, obj) {
            return tot + (+obj.balance || 0);
        }, 0);
        console.log(sumOfBalances);
        console.log("All Done");
    });

objcalculateApiBalances()$.getJSON(someurl) promise 的对象。如果出现 $.getJSON() 错误,obj 将是 jqXHR 对象,obj.balance 将是 undefined+obj.balance 将为 NaN,因此默认添加零;否则添加 obj.balance 。

如果您想知道有多少 getJSON 请求成功,有多少不成功,那么还需要编写一些代码,但不是很多。

关于javascript - 在jquery中获取多个延迟对象的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29816137/

相关文章:

javascript - 如果 div 为空,则添加警报

javascript - 如何使用 jQuery 强制对 GET 请求进行字符串响应?

javascript - 如何知道是否从 javascript 控制台调用了一个函数?

javascript - 如何使用 React 从 JSON 对象加载图像?

javascript - 区分 AJAX 上的多种表单

javascript - 拉斐尔将元素放置在右侧并在那里缩放

javascript - jQuery 选项卡问题

javascript - jQuery 倒计时 onExpiry 函数?

javascript - Socket.emit无法触发socket.on

javascript - 用文本替换 textarea 中的 html 标签