Skip to content

Instantly share code, notes, and snippets.

@linx4200
Created June 25, 2018 09:03
Show Gist options
  • Save linx4200/767e4bb7129aaf3b036dba3ade23f8f3 to your computer and use it in GitHub Desktop.
Save linx4200/767e4bb7129aaf3b036dba3ade23f8f3 to your computer and use it in GitHub Desktop.
依次(串行)执行多项异步任务
// method 1:
function sequence(tasks, fn) {
return tasks.reduce(
(promise, task) => promise.then(() => fn(task)),
Promise.resolve()
)
}
// method 2:
async function taskReducer(promise, action){
let res = await promise;
return action(res);
}
function sleep(ms){
return new Promise(resolve => setTimeout(resolve, ms));
}
async function asyncTask(i){
await sleep(500);
console.log(`task ${i} done`);
return ++i;
}
[asyncTask, asyncTask, asyncTask].reduce(taskReducer, 0);
@linx4200
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment