var fs = require('fs');
var readFile = function ( fileName ) {
return new Promise(function ( resolve, reject ) {
fs.readFile(fileName, function ( err, data ) {
if (err) {
return reject(err);
}
return 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());
};
/*
g.next().value.then(function ( data ) {
g.next(data).value.then(function ( data ) {
g.next(data);
});
});
*/
var run = function () {
let g = gen();
let next = function ( data ) {
let result = g.next(data);
if (result.done) {
return result.value;
}
result.value.then(function (data) {
next(data);
});
};
next();
};
run(gen);
// spawn自動執(zhí)行器函數(shù)的實(shí)現(xiàn)
var spawn = function ( genFunc ) {
return new Promise(function ( resolve, reject ) {
let g = genFunc();
let next = function (nextFunc) {
try {
let nextF = nextFunc();
if (nextF.done) {
return resolve(nextF.value);
}
Promise.resolve(nextF.value)
.then(
function ( v ) {
next(function () {
return g.next(v);
});
},
function ( e ) {
next(function () {
return g.throw(e);
});
});
} catch (e) {
return reject(e);
}
};
next(function () {
// return g.next(undefined);
return g.next();
});
});
};
spawn(gen)
.then(function () {
console.log("function success ...");
})
.catch(function ( e ) {
console.log(e);
});
手動執(zhí)行Generator函數(shù)鼓黔,其實(shí)就是用then方法旭旭,層層添加回調(diào)函數(shù)谎脯。
var g = gen();
g.next().value.then(function ( data ) {
g.next(data).value.then(function ( data ) {
g.next(data);
});
});