$.when 函数数组无法正常工作
$.when with arrays of functions is not working properly
我要解决的问题: 我想要两个 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 是包含所有这些代码的 fiddle,以便能够对其进行测试和修改。
参考资料:我试图从这个 page 的工作示例中修改以解决我的问题。
$.when
不接受或期望函数数组,它期望 deferreds 数组。您需要调用您的函数,并传递 promise。
var topPriorityPromises = [];
topPriorityFunctions.push(showDiv());
topPriorityFunctions.push(getData());
$.when.apply($, topPriorityPromises ).then(function () {
// ...
如果您简化它并忽略 array/apply 部分,您将以这种方式调用 when
,这是错误的:
$.when(showDiv, getData);
不是这样,正确的是:
$.when(showDiv(), getData());
我要解决的问题: 我想要两个 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 是包含所有这些代码的 fiddle,以便能够对其进行测试和修改。
参考资料:我试图从这个 page 的工作示例中修改以解决我的问题。
$.when
不接受或期望函数数组,它期望 deferreds 数组。您需要调用您的函数,并传递 promise。
var topPriorityPromises = [];
topPriorityFunctions.push(showDiv());
topPriorityFunctions.push(getData());
$.when.apply($, topPriorityPromises ).then(function () {
// ...
如果您简化它并忽略 array/apply 部分,您将以这种方式调用 when
,这是错误的:
$.when(showDiv, getData);
不是这样,正确的是:
$.when(showDiv(), getData());