Ben*_*ter 2 javascript jquery jquery-deferred
等待多个延迟对象完成时,为什么:
$.when(tasks).then(function() {
document.write("Completed all requests." + "<br/>");
});
Run Code Online (Sandbox Code Playgroud)
立即执行
$.when.apply(null, tasks).then(function () {
document.write("Completed all requests." + "<br/>");
});
Run Code Online (Sandbox Code Playgroud)
等到任务完成.
Jos*_*ber 11
该when
函数不采用延迟数组.相反,您将每个延迟传递为单独的参数.这正是apply
为你做的.
将null
被传递到apply
仅仅是因为这是apply
预计:第一个参数是什么功能的情况下,应设置为它的调用时,第二个参数始终是一个数组,这将扩大,这样的功能将被称为如果数组中的所有项都已作为单独的参数传入.
因为when
它的目的与它所调用的上下文没有区别,所以与null
其他任何东西一样有效.我更喜欢传递jQuery本身:
$.when.apply($, tasks).then(function () {
// Whatever
});
Run Code Online (Sandbox Code Playgroud)
因为我认为它看起来更干净,但那只是我.它没有任何区别.
如果您的浏览器支持本机承诺(或者您正在使用polyfill),则可以使用其all
方法,它直接采用一系列承诺:
Promise.all(tasks).then(function (values) {
// "values" is an array, with the results of each of the "tasks"
});
Run Code Online (Sandbox Code Playgroud)