Created
June 25, 2018 09:03
-
-
Save linx4200/767e4bb7129aaf3b036dba3ade23f8f3 to your computer and use it in GitHub Desktop.
依次(串行)执行多项异步任务
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
method1:
nuxt/lib/common/utils.js
method2:
https://www.h5jun.com/post/three-black-tech-in-modern-js.html?hmsr=toutiao.io&utm_medium=toutiao.io&utm_source=toutiao.io