jQuery Deferreds的异步循环(承诺) [英] Asynchronous Loop of jQuery Deferreds (promises)
问题描述
我正在努力创造我认为被称为瀑布的东西。我想顺序处理一系列异步函数(jQuery promises)。
I am trying to create what I think is referred to as a "Waterfall". I want to sequentially process an array of async functions (jQuery promises).
这是一个人为的例子:
function doTask(taskNum){
var dfd = $.Deferred(),
time = Math.floor(Math.random()*3000);
setTimeout(function(){
console.log(taskNum);
dfd.resolve();
},time)
return dfd.promise();
}
var tasks = [1,2,3];
for (var i = 0; i < tasks.length; i++){
doTask(tasks[i]);
}
console.log("all done");
我希望它按照执行顺序完成任务(存在于数组中)。因此,在这个例子中,我希望它执行任务1并等待它解决然后执行任务2等待它解决,执行任务3等并且日志全部完成。
I would like it to complete the task in the order they are executed (present in the array). So, in this example I want it to do task 1 and wait for it to resolve then do task 2 wait for it to resolve, do task 3 etc and the log "all done".
也许这很明显,但我一直试图在整个下午解决这个问题。
Maybe this is really obvious but I've been trying to figure this out all afternoon.
推荐答案
我尝试使用 $()。队列
而不是 $。延期
这里。将函数添加到队列中,并在准备好时仅调用下一个函数。
I'd try using $().queue
instead of $.Deferred
here. Add the functions to a queue, and only call the next one when ready.
function doTask(taskNum, next){
var time = Math.floor(Math.random()*3000);
setTimeout(function(){
console.log(taskNum);
next();
},time)
}
function createTask(taskNum){
return function(next){
doTask(taskNum, next);
}
}
var tasks = [1,2,3];
for (var i = 0; i < tasks.length; i++){
$(document).queue('tasks', createTask(tasks[i]));
}
$(document).queue('tasks', function(){
console.log("all done");
});
$(document).dequeue('tasks');
这篇关于jQuery Deferreds的异步循环(承诺)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!