1.回调函数(产生回调地狱) 2.Promise(摆脱回调地狱问题) 3.Generator生成器函数(实现了流程控制) 4.async await(异步最终解决方案 基于Generator和Promise实现) yield中途暂停点 next()下一步 async await的实现是依靠 generator生成器函数+promise实现的
在generator函数的yield后面接promise
但返回的是promise对象 使用promise.then方法得到具体的值 generator还可以用next方法传参,并且可以通过yield来接受参数
function fn(nums) {
return new Promise(resolve => {
setTimeout(() => {
resolve(nums * 2)
}, 1000)
})
}
function* gen() {
const num1 = yield fn(1)
const num2 = yield fn(num1)
const num3 = yield fn(num2)
return num3
}
const g = gen()
const next1 = g.next()
next1.value.then(res1 => {
console.log(next1)
console.log(res1)
const next2 = g.next(res1)
next2.value.then(res2 => {
console.log(next2)
console.log(res2)
const next3 = g.next(res2)
next3.value.then(res3 => {
console.log(next3)
console.log(res3)
console.log(g.next(res3))
})
})
})
但还存在三个问题 gen函数执行返回值不是Promise,asyncFn执行返回值是Promise gen函数需要执行相应的操作,才能等同于asyncFn的排队效果 gen函数执行的操作是不完善的,因为并不确定有几个yield,不确定会嵌套几次
解决第一个问题 使用高阶函数
function* gen() {
}
function generatorToAsync (generatorFn) {
return function () {
return new Promise((resolve, reject) => {
})
}
}
const asyncFn = generatorToAsync(gen)
console.log(asyncFn())
最终结果
function fn(nums) {
return new Promise(resolve => {
setTimeout(() => {
resolve(nums * 2)
}, 1000)
})
}
function* gen() {
const num1 = yield fn(1)
const num2 = yield fn(num1)
const num3 = yield fn(num2)
return num3
}
function generatorToAsync(generatorFn) {
return function () {
return new Promise((resolve, reject) => {
const g = generatorFn()
const next1 = g.next()
next1.value.then(res1 => {
const next2 = g.next(res1)
next2.value.then(res2 => {
const next3 = g.next(res2)
next3.value.then(res3 => {
resolve(g.next(res3).value)
})
})
})
})
}
}
const asyncFn = generatorToAsync(gen)
asyncFn().then(res => console.log(res))
|