使用异步方法按顺序运行功能 [英] Running function with async method in sequential order

查看:45
本文介绍了使用异步方法按顺序运行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内部带有异步方法的函数数组.我想创建一个函数,该函数采用函数数组并按顺序执行该函数.我不确定如何实现.感谢帮助.本质上不是异步的.它是每个函数中的方法

I have an array of function with async method inside it.I want to create a function which takes the array of function and execute the function in sequential order.I am not sure how to achieve it.Thanks for help.The functions are not async in nature.Its the method inside each functions

示例.

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');
}

推荐答案

经典答案

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

Classic answer

You'll have to accept callbacks to achieve this, e.g.

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([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>

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());
}

这篇关于使用异步方法按顺序运行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆