async实现

参考一: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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值