【问题标题】:$.when with arrays of functions is not working properly$.when 函数数组无法正常工作
【发布时间】:2015-04-27 13:22:01
【问题描述】:

我要解决的问题:我想要两个 ajax 函数数组。一个应该首先运行的 topPriority,另一个具有低优先级的将在所有 topPriority 调用完成后立即启动。

然而,这个函数甚至没有在$.when 行中被调用。我使用正确吗?

//HTML:

<div id="foo">Hello World</div>

//CSS:

#foo{ border:1px solid red; padding:10px; display:none }

//Javascript:

// open your console!

function getData(){
   return $.get('/echo/html/');
}

function showDiv(){
    var dfd = $.Deferred();

    $('#foo').fadeIn( 1000, dfd.resolve );

    return dfd.promise();
}

var topPriorityFunctions = new Array();
topPriorityFunctions.push(showDiv);
topPriorityFunctions.push(getData);

$.when.apply($, topPriorityFunctions )
    .then(function( ajaxResult ){
        console.log('The animation AND the AJAX request are both done!');

        // ‘ajaxResult’ is the server’s response
        // start my lowPriorityTasks.
    });

Here 是所有这些代码的小提琴,以便能够对其进行测试和修改。

参考:我试图从这个page 上的工作示例进行修改,以解决我的问题。

【问题讨论】:

  • 不要将dfd.resolve直接作为回调传递。 resolve() 将被调用,this 绑定到 $("#foo")[0] 而不是 dfd,这很可能会破坏实现。传递一个调用dfd.resolve() 的匿名函数。
  • 注意:您可以将$('#foo').fadeIn( 1000, dfd.resolve ) 更改为简单的return $('#foo').fadeIn(1000).promise(),因为这将返回动画队列承诺
  • 感谢@frédéricHamidi。我不太明白你的解释。为什么我的函数甚至没有被调用?我真的不太关心函数 showDiv 是一个 Deferred 对象,因为我的问题实际上有点不同。我所有的函数都只是 ajax 调用。
  • @cacho,看起来像一个小提琴问题。使用 jQuery (edge),我的浏览器显示 Blocked loading mixed active content "http://code.jquery.com/jquery-compat-git.js"。使用 jQuery 2.1.0 调用函数。
  • @TrueBlueAussie,假设在 1 秒延迟期间 #foo 上没有启动其他动画,是的。

标签: jquery ajax jquery-deferred .when


【解决方案1】:

$.when 不接受或期望一个函数数组,它期望一个 deferreds 数组。你需要调用你的函数,并传入 Promise。

var topPriorityPromises = [];
topPriorityFunctions.push(showDiv());
topPriorityFunctions.push(getData());

$.when.apply($, topPriorityPromises ).then(function () {
  // ...

如果您简化此操作并忽略数组/应用部分,您会以这种方式调用 when,这是错误的:

$.when(showDiv, getData);

不是这样,这是正确的:

$.when(showDiv(), getData());

【讨论】:

  • 感谢@meagar。问题是我实际上不需要延迟函数,我只有一个包含 10 个 ajax 调用的数组。但是,我需要其中 3 个首先完成(最高优先级),然后我想调用其余 7 个 ajax 调用(低优先级)。
  • 在这种情况下,我还能将 $.when.apply( ) 与一组 ajax 调用函数一起使用吗?
  • 您有 3 个可以独立工作的 url,其他 7 个取决于前 3 个的累积响应。这是您想要的吗?顺便说一句,也检查一下..jsfiddle.net/JSw5y/1168
  • @Vishwanath 不,实际上所有请求都可以独立运行。我只想给其中 3 个优先级,因为我希望他们先完成。
  • @cacho 这与 $.when 或您在问题中发布的代码无关。您不能使用$.when 来“提高”您的 AJAX 调用的优先级。只需先完成它们。我的回答回答了您提出的问题,这就是 $.when 不调用您的函数的原因。如果您想围绕这个优先概念展开讨论,请提出一个新问题。
猜你喜欢
  • 2016-01-12
  • 2019-09-14
  • 2017-12-15
  • 2013-03-27
  • 2012-08-15
  • 2013-11-05
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
相关资源
最近更新 更多