使用异步方法按顺序运行函数

时间:2018-02-25 17:22:57

标签: javascript asynchronous

我有一个带有异步方法的函数数组。我想创建一个函数,它接受函数数组并按顺序执行函数。我不知道如何实现它。谢谢你的帮助。函数本质上不是异步的。它是每个函数内部的方法

实施例。

function task1() {
  console.log('task1:started');
  setTimeout(function() {
    console.log('task1:finished');
  }, 5000);
}

function task2() {
  console.log('task2:started');
  setTimeout(function() {
    console.log('task2:finished');
  }, 5000);
}

function runner(tasks) {
  // help with implementation needed
  console.log('Desired Output:');
  console.log('task1: started');
  console.log('task1: finished');

  console.log('task2: started');
  console.log('task2: finished');
}

1 个答案:

答案 0 :(得分:2)

经典答案

您必须接受回调才能实现这一目标,例如



runner([task1, task2], function() {
  console.log('tasks done!');
})

function task1(cb) {
  console.log('task1:started');
  setTimeout(function() {
    console.log('task1:finished');
    cb();
  }, 100);
}

function task2(cb) {
  console.log('task2:started');
  setTimeout(function() {
    console.log('task2:finished');
    cb();
  }, 100);
}

function runner(tasks, cb) {
  if (!tasks.length) {
    return cb();
  }

  let index = 0;

  function run() {
    var task = tasks[index++]

    task(index === tasks.length ? cb : run);
  }

  run();
}




使用async.waterfall



async.waterfall([task1, task2], function() {
  console.log('tasks done!');
})

function task1(cb) {
  console.log('task1:started');
  setTimeout(function() {
    console.log('task1:finished');
    cb();
  }, 100);
}

function task2(cb) {
  console.log('task2:started');
  setTimeout(function() {
    console.log('task2:finished');
    cb();
  }, 100);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/async/2.6.0/async.js"></script>
&#13;
&#13;
&#13;

基于承诺的实施

&#13;
&#13;
runner([task1, task2]).then(() => {
  console.log('tasks done')
})

function task1(cb) {
  return new Promise(resolve => {
    console.log('task1:started');
    setTimeout(function() {
      console.log('task1:finished');
      resolve();
    }, 200);
  });
}

function task2(cb) {
  return new Promise(resolve => {
    console.log('task2:started');
    setTimeout(function() {
      console.log('task2:finished');
      resolve();
    }, 100);
  });
}

function runner(tasks, cb) {
  return tasks.reduce((job, task) => job.then(task), Promise.resolve());
}
&#13;
&#13;
&#13;