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函数,执行流程是这样的:
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 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来用,总之感觉还是蛮赞的~