【问题标题】:jQuery $when.apply() .. then() firing for each completed requestjQuery $when.apply() .. then() 为每个完成的请求触发
【发布时间】:2014-01-07 05:35:57
【问题描述】:

这是我在 ASP.NET MVC Razor 视图中创建的 jQuery 方法。所需的功能是:

  • 选择文本区域
  • 触发一组 ajax 请求
  • 所有 ajax 请求完成后,显示警报对话框

代码似乎工作正常,除了多次显示警告“确定”对话框,每个请求一次。这表明正在为每个请求调用 .then() 方法,而不是等待所有请求完成。我在这里做错了什么?

// Save changed entity notes
function saveChangedNotes() {

  var ajaxReqs = [];
  $('textarea').each(function() {
    ajaxReqs.push($.ajax({
        type: "POST",
        url: "@Url.Action("UpdateCompanyNote", "Company", new {companyId = Html.CompanyIdFromRouteValues()})",
        data: {
          noteId: this.id,
          noteText: $(this).val()
        }
      })
    );

    // When all ajax complete..
    $.when.apply($, ajaxReqs).then(function() {      
      alert('ok');
    }).fail(function() {         
      alert('error');
    });
  });
}

【问题讨论】:

    标签: ajax jquery promise


    【解决方案1】:

    您在每个循环中执行$.when.apply inside textarea。数一数你的右括号。

    【讨论】:

    • Duh.. 我以为是我误解了承诺 :) 谢谢,好地方
    【解决方案2】:

    有一种更简单的替代方法完全不使用$.when.apply 和数组

    改为使用模式promise = $.when(promise, anotherPromise)

    例如对于你的例子是这样的

    // Save changed entity notes
    function saveChangedNotes() {
        // Start with a resolved promise (undefined does the same thing for $.when!)
        var promise;
        $('textarea').each(function () {
            promise = $.when(promise, $.ajax({
                type: "POST",
                url: "@Url.Action("
                UpdateCompanyNote ", "
                Company ", new {companyId = Html.CompanyIdFromRouteValues()})",
                data: {
                    noteId: this.id,
                    noteText: $(this).val()
                }
            }));
        });
        // When all ajax complete..
        promise.then(function () {
            alert('ok');
        }).fail(function () {
            alert('error');
        });
    }
    

    【讨论】:

    • 我凭直觉也这样做了——使用数组和带有副作用的编码对于函数式 jquery apporach 来说似乎是不自然的。但我认为它应该只是promise,而不是最后一个语句中的$promise。只是一个错字。
    • @Alex Pakka:谢谢。是的,这是一个剪切/粘贴错字。干杯
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 2020-07-06
    • 2016-05-27
    • 1970-01-01
    • 2017-09-12
    • 2018-07-09
    相关资源
    最近更新 更多