利用ES6 的generators 化异步为同步

generator可以将异步转化为同步,让JS中讨厌的回调清晰起来。

如下例:

var fs = require('fs')

function run(generator){

  console.log('now in run')

  var it = generator(go)

  console.log(`now get it : ${it}`)

  function go(err,result){
    console.log(`now in go, err is 
      ${err},result is 
      ${result}`)

    var next = it.next(result)

    console.log(`now after it.next and its value and done : ${next.value},${next.done}`)
  }

  go()

  console.log(`end of function run`)

}

run(function* (done){

  console.log(`before var exercises`)

  var exercises = yield fs.readFile('gulp.js',done)

  console.log(`exercises is ${exercises}`)

})

在console台的结果是这样:

now in run
now get it : [object Generator]
now in go, err is 
      undefined,result is 
      undefined
before var exercises
now after it.next and its value and done : undefined,false
end of function run
now in go, err is 
      null,result is 
      var gulp= require('gulp');
var htmlmin=require('html-minifier');

gulp.task('minifyhtml',function(){

    gulp.src('myjq.html')
    .pipe(htmlmin({collapseWhitespace:true}))
    .pipe(gulo.dest('./dist'))
})
exercises is var gulp= require('gulp');
var htmlmin=require('html-minifier');

gulp.task('minifyhtml',function(){

    gulp.src('myjq.html')
    .pipe(htmlmin({collapseWhitespace:true}))
    .pipe(gulo.dest('./dist'))
})
now after it.next and its value and done : undefined,true

关键就在这个run函数,执行流程是这样的:

  1. 新建一个generator-iterator对象(it)
  2. 定义go函数,在go函数中调用了it.next
  3. 将go函数传给了genterator-iterator对象作为回调
  4. 不带参数地运行go函数一次,来初始化generator

go函数总共被执行了两次,一次不带参数,第二次拿到了yield fs的结果再做下面的事情。

还可以把fs.readFile包装成另一个函数,再看

function run(taskdef){

  let task = taskdef()

  let next = task.next()

  console.log(`刚进run函数 next,${next.value}`)

  function step(){

    console.log('in step')

    if(!next.done){

      if(typeof next.value === 'function'){

        console.log(`type func`,next.value)

        next.value( function(err,data){

          if(err){

            console.error('err happend', err)

            task.throw(err)

            return
          }

          console.log('data happed',data)

          next = task.next(data)

          console.log(`next= task.next(data),${next.value},${next.done}`)

          step()


        })
      }

      else{ // else 部分始终没有执行到

        console.log(`now value not func, ${next.value}`)

        next = task.next(  next.value )

        console.log(`in else module , nextvalue = ${next.value}`)

        step()

      }
    }

  }


  step()

}

let fs = require('fs')

function readFile(filename){

  return function(callback){

    fs.readFile(filename,callback)
  }

}

run(function* (){

  let contents = yield readFile('gulp.js')

  console.log(`contents happed ,${contents}`)

  console.log('done')
})

console台的结果是:

刚进run函数 next,function (callback){

    fs.readFile(filename,callback)
  }
in step
type func function (callback){

    fs.readFile(filename,callback)
  }
data happed <Buffer 76 61 72 20 67 75 6c 70 3d 20 72 65 71 75 69 72 65 28 27 67 75 6c 70 27 29 3b 0a 76 61 72 20 68 74 6d 6c 6d 69 6e 3d 72 65 71 75 69 72 65 28 27 68 74 ... >
contents happed ,var gulp= require('gulp');
var htmlmin=require('html-minifier');

gulp.task('minifyhtml',function(){

    gulp.src('myjq.html')
    .pipe(htmlmin({collapseWhitespace:true}))
    .pipe(gulo.dest('./dist'))
})
done
next= task.next(data),undefined,true
in step

这块不是很好理解,建议自己敲一遍代码试试。

然后它还可以结合promise来用,总之感觉还是蛮赞的~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值