//my three functions...
function wait1() {
setTimeout(function(){
console.log('hello, this is the function 1');
return 'ok';
},2000)
}
function wait2() {
setTimeout(function(){
console.log('hello, this is the function 2');
return 'ok';
},2000)
}
function wait3() {
setTimeout(function(){
console.log('hello, this is the function 3');
return 'ok';
},2000)
}
var tasks = [wait1,wait2,wait3];
var counter = 0;
function iterateTasks(tasks) {
runSequence(tasks[counter], function(){
counter++;
if(counter < tasks.length) {
iterateTasks(tasks);
}
});
}
//@params func received function
//@params cb received callback function
function runSequence(func,cb) {
var timeout = 0;
var tmr = setInterval(function(){
if(func() === 'ok' || timeout === 5000) {
console.log('OK, func = ', func);
cb();
clearInterval(tmr);
timeout = 0;
}
timeout += 500;
},500);
}
//start program...
iterateTasks(tasks);
感谢任何帮助!
答案 0 :(得分:0)
尝试为每个函数添加回调:
//my three functions...
function wait1(callback) {
setTimeout(function(){
console.log('hello, this is the function 1');
callback('ok');
},2000)
}
function wait2(callback) {
setTimeout(function(){
console.log('hello, this is the function 2');
callback('ok');
},2000)
}
function wait3(callback) {
setTimeout(function(){
console.log('hello, this is the function 3');
callback('ok');
},2000)
}
var tasks = [wait1,wait2,wait3];
var counter = 0;
function iterateTasks(tasks, callback) {
setTimeout(function req(){
tasks[counter++](function(value) {
if (counter == tasks.length) {
if (typeof callback == 'function') {
callback();
}
} else if (value === 'ok') {
setTimeout(req, 500);
}
});
}, 500);
}
//start program...
iterateTasks(tasks);
答案 1 :(得分:-1)
承诺很好,但你也可以通过生成器的懒惰评估完成这项工作。我们来看看它是如何实现的。
function* runner(functions,text){
var val = text;
for (var fun of functions) {
val = yield fun(val);
}
}
function wait1(t) {
setTimeout(function(){
console.log(t + "1");
it.next(t);
},2000);
}
function wait2(t) {
setTimeout(function(){
console.log(t + "2");
it.next(t);
},2000);
}
function wait3(t) {
setTimeout(function(){
console.log(t + "3");
it.next(t);
},2000);
}
var tasks = [wait1,wait2,wait3],
it = runner(tasks, "Hello this is function #");
it.next(); // start the engine...!