【问题标题】:jQuery .when() is getting ignored in a loopjQuery .when() 在循环中被忽略
【发布时间】:2016-05-18 13:04:54
【问题描述】:

我有一个自定义循环,需要在进入下一次迭代之前执行一个函数。这是代码:

function customIteration(arr, i)
{
    if (i==arr.length) return;
    var message = arr[i];
    jQuery('#stepTwo #num1StepTwo').html('Expires: ' + $num1);
    jQuery('#stepTwo #num2StepTwo').html(jQuery(message).find('.num2').text());
    jQuery('#stepTwo #num3StepTwo').html(jQuery(message).find('.num3').text());
    i++;
    jQuery.when(mySpecialFunction()).then(customIteration(arr, i));
}

mySpecialFunction():

function mySpecialFunction(){
    return jQuery.ajax({
        url: "https://api.site.com/customurl",
        dataType: "jsonp",
        data: { data1: $data1, data2: $data2 },
        success: function (data) {
            ...some code...
        },
        error: function (e) {
            ...some other code...
        }
    });
}

问题是,我在 Fiddler 中看到,上面循环的所有实例都会立即点击该 url,而无需等待从 mySpecialFunction() 中的 ajax 代码获得响应。这当然会弄乱我应该得到的结果。

【问题讨论】:

  • .then(customIteration(arr, i)) 更改为.then(function(){ customIteration(arr, i) })
  • @A1rPun 这确实有效!非常感谢。

标签: javascript jquery ajax loops .when


【解决方案1】:

尝试使用 .done()

事实上,

.done() 只有成功回调。

.then() 有成功和失败的回调。

从 jQuery 1.8 开始,deferred.then() 方法返回一个新的 Promise,它可以通过函数过滤 deferred 的状态和值,替换现已弃用的 deferred.pipe() 方法。

deferred.done() 方法接受一个或多个参数,所有参数都可以是单个函数或函数数组。

由于 deferred.done() 返回延迟对象,延迟对象的其他方法可以链接到这个,包括附加的 .done() 方法。当 Deferred 被解析时,doneCallbacks 会使用提供给 resolve 或 resolveWith 方法调用的参数按照它们被添加的顺序执行。

【讨论】:

    【解决方案2】:

    尝试使用 .done() 和递归函数,应该更容易实现和理解。 像这样:

     (function recursive(arr,i){
       jQuery.ajax({
        url: "https://api.site.com/customurl",
        dataType: "jsonp",
        data: { data1: $data1, data2: $data2 },
        success: function (data) {
            ...some code...
        },
        error: function (e) {
            ...some other code...
        }
    }).done(function(data){
           var message = arr[i];
           jQuery('#stepTwo #num1StepTwo').html('Expires: ' + $num1);
           jQuery('#stepTwo#num2StepTwo').html(jQuery(message).find('.num2').text());
           jQuery('#stepTwo #num3StepTwo').html(jQuery(message).find('.num3').text());
           if(i!=arr.length){
           recursive(++i); 
           }
     }); /// End done
    })(0); ///End recursive function
    

    这样做是确保您的单次迭代结束,然后再次调用自身并继续迭代。 所以基本上你的函数在一次迭代完成时会调用自己,并继续直到所有内容都被迭代,然后停止。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-04
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多