async 函数实现

async函数的实现: generator iterator co

 

async function read(){

  let template = await readFile(‘./teamplate.txt’)

  let data = await readFile(‘./data.txt’)

  return template + data

}

 

 等价于 

function read() {

  return co( function *(){

    let template = yield readFile(‘./template.txt’)

    let data = yield readFile(‘./data.txt’)

    return template + data

  })

}

 

 

 

co包裹函数:

 

function co(gen){
  const it = gen()
  return new Promise((resolve,reject)=>{
    (function next(lastVal){
      const {value,done} = it.next(lastVal)
      if(!done){
        return Promise.resolve(value).then(next,err=>reject(err))
      }else{
        resolve(value)
      }
    })()
  })
}

posted @ 2023-02-22 17:30  hh9515  阅读(36)  评论(0编辑  收藏  举报