参考一:async函数
参考二:await语法
参考三:7张图,20分钟就能搞定的async/await原理
async函数本质是Promise函数的一个语法糖,作用是以同步方式,执行异步操作
,底层实现用generator
函数对promise进行一层封装,最终返回的也会是一个promise
function fn(nums) {
return new Promise(resolve => {
setTimeout(() => {
resolve(nums * 2)
}, 1000)
})
}
// async调用
async function test(){
const num1 = await fn(1)
const num2 = await fn(num1)
const num3 = await fn(num2)
return num3
}
let data = test()
// 用generator函数模拟async
function* gen() {
const num1 = yield fn(1)
const num2 = yield fn(num1)
const num3 = yield fn(num2)
return num3
}
let data = null
const g = gen()
const next1 = g.next()
next1.value.then(res1 => {
const next2 = g.next(res1)
next2.value.then(res2 => {
const next3 = g.next(res2) // 传入上次的res2
next3.value.then(res3 => {
data = g.next(res3).value
})
})
})
基于generator模拟过程进行async实现,以yield
代替await
关键字
function genFnToAsync(generatorFn){
return function(){
let gen = generatorFn.apply(this,arguments)
return new Promise((resolve,reject)=>{
go('next')
function go(key,arg){
let res
try {
res = gen[key](arg)
} catch (e) {
return reject(e)
}
const {value,done} = res
if(done) return resolve(value)
else Promise.resolve(value).then(val=>go('next',val),e=>go('throw',e))
}
})
}
}
// test
function fn(nums) {
return new Promise(resolve => {
setTimeout(() => {
resolve(nums * 2)
}, 1000)
})
}
function *genGetData(){
let res1 = yield fn(1)
let res2 = yield fn(res1)
let res3 = yield fn(res2)
let res4 = yield fn(res3)
return res4
}
let asyncGetData = genFnToAsync(genGetData)
asyncGetData().then(res=>console.log(res)) // 16