如何按顺序运行javascript函数并等待每个函数完成

时间:2016-09-07 14:45:09

标签: javascript

基本上,我有三个函数,我想要的是按顺序运行所有这三个函数(同步),每个函数等待前一个函数完成。我把超时放在函数中来模拟时间执行,我不知道这是否有效。我的代码是。

//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);

感谢任何帮助!

2 个答案:

答案 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...!