问题描述:

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.

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
相关阅读:
Top