简体   繁体   English

使用jquery推迟而不是回调

[英]using jquery deferred instead of callback

I'm trying to resolve an array of task (array is dynamic), these tasks are async and I need to make sure previous task success before the next ask. 我正在尝试解析一个任务数组(数组是动态的),这些任务是异步的,在下一个询问之前,我需要确保上一个任务成功。 so far this is what I have: 到目前为止,这就是我所拥有的:

var tasks = ['cleaning', 'washing', 'shopping'];

var index = 0;

while(index < tasks.length) {
  // success => next task
  // fail => exit
  index++;
}

function doTask(name) {
    var d = $.Deferred();
    console.log('doing ' + name);
    setTimeout(function() {
        d.resolve(name + ' is done');
    }, 1000); 
    return d.promise();
}

// my old method
function doTask(name, callback) {
    console.log('doing ' + name);
    setTimeout(function() {
        callback(name + ' is done');
    }, 1000);
}

so the output would be 所以输出将是

// doing cleaning
// cleaning is done
// doing washing
// washing is done
// doing shopping
// shopping is done

thanks for the help! 谢谢您的帮助!

var tasks = ['cleaning', 'washing', 'shopping'];
var index = 0;

function asyncTasks(tasks_length){
 $.when(doTask(tasks[index])).then(function(res){
   console.dir(res);
   index++;
   if(index<tasks_length){
     asyncTasks(tasks_length);
   } else {return;}
 }, function(){return;})
}

function doTask(name) {
    var d = $.Deferred();
    console.log('doing ' + name);
    setTimeout(function() {
        d.resolve(name + ' is done');
    }, 1000); 
    return d.promise;
}

asyncTasks(tasks.length);

Smth like this, not sure in syntax, usially work with angular promises 像这样的东西,语法不确定,通常可以与角度承诺一起使用

In your doTask() function replace code with d.promise() for getting promise object, Code below will execute only in all previous promises are done. doTask()函数中,用d.promise()替换代码以获得诺言对象,下面的代码将仅在所有以前的诺言完成后执行。

var tasks = ['cleaning', 'washing', 'shopping'];

function doTask(name) {
    var d = $.Deferred();
    console.log('doing ' + name);
    setTimeout(function() {
        d.resolve(name + ' is done');
    }, 1000); 
    return d.promise();
}

var d1 =doTask(tasks[0]);
var d2 =doTask(tasks[1]);
var d3 =doTask(tasks[2]);


$.when( d1, d2,d3 ).done(function (w1,w2,w3) {
   console.log(w1,w2,w3);
   // Success call back
});

Output: 输出:

doing cleaning 
doing washing
doing shopping

 cleaning is done
 washing is done
 shopping is done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM