事件发布/订阅
function fn1(){
console.log('fn1')
asyncFun.next()
}
function fn2(){
setTimeout(() => {
console.log('fn2')
asyncFun.next()
}, 500)
}
function fn3(){
console.log('fn3')
asyncFun.next()
}
class AsyncFun {
constructor (...arr){
this.funcArr = [...arr]
}
next(){
const fn = this.funcArr.shift()
if(typeof fn === 'function') fn()
}
run(){
this.next()
}
}
const asyncFun = new AsyncFun(fn1, fn2, fn3)
asyncFun.run()
//fn1
//fn2
//fn3
Promise
function fn1 () {
console.log('Function 1')
}
function fn2 () {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Function 2')
resolve()
}, 500)
})
}
function fn3 () {
console.log('Function 3')
}
fn1()
fn2().then(() => {fn3()})
//Function 1
//Function 2
//Function 3
Generator
function fn1 () {
console.log('Function 1')
}
function fn2 () {
setTimeout(() => {
console.log('Function 2')
func.next()
}, 500)
}
function fn3 () {
console.log('Function 3')
}
function* asyncFun(...fn){
fn[0]()
yield fn[1]()
fn[2]()
}
const func = asyncFun(fn1, fn2, fn3)
func.next()
//Function 1
//Function 2
//Function 3
Async
function fn1 () {
console.log('Function 1')
}
function fn2 () {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Function 2')
resolve()
}, 500)
})
}
function fn3 () {
console.log('Function 3')
}
async function asyncFun(){
fn1()
await fn2()
fn3()
}
asyncFun()
//Function 1
//Function 2
//Function 3