首页 > 代码库 > ES6.0 Generator 三种用法

ES6.0 Generator 三种用法

// Generator start -------  thunk 用法

const Thunk = function(fn) {
return function (...args) {
return function (callback) {
return fn.call(this, ...args, callback);
}
};
};
const run_thunk = function (fn) {
var gen = fn();

function next(data) {
var result = gen.next(data);
if (result.done) return;
result.value(next);
}
next();
}

var readFile = Thunk(fs.readFile);
function* g() {
var f1 = yield readFile(‘fileA‘);
var f2 = yield readFile(‘fileB‘);
// ...
var fn = yield readFile(‘fileN‘);
}
run_thunk(g);

---------- promise用法
function run_promise(gen){
var g = gen();

function next(data){
var result = g.next(data);
if (result.done) return result.value;
result.value.then(function(data){
next(data);
});
}
next();
}

var fs = require(‘fs‘);

var readFile = function (fileName){
return new Promise(function (resolve, reject){
fs.readFile(fileName, function(error, data){
if (error) return reject(error);
resolve(data);
});
});
};

var gen = function* (){
var f1 = yield readFile(‘/etc/fstab‘);
var f2 = yield readFile(‘/etc/shells‘);
console.log(f1.toString());
console.log(f2.toString());
};

run_promise(gen);


// -----------co 用法

var gen = function* () {
var f1 = yield readFile(‘/etc/fstab‘);
var f2 = yield readFile(‘/etc/shells‘);
console.log(f1.toString());
console.log(f2.toString());
};

// var co = require(‘co‘);
// co(gen);
// co(gen).then(function (){
// console.log(‘Generator 函数执行完成‘);
// });

//------------co end

// Generator end -------

ES6.0 Generator 三种用法