使用异步方法按顺序运行功能
问题描述:
我有一个内部带有异步方法的函数数组.我想创建一个函数,该函数采用函数数组并按顺序执行该函数.我不确定如何实现.感谢帮助.本质上不是异步的.它是每个函数中的方法
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());
}