标签:模块 func thunk next bsp settime turn reject llb
promise方式:
// 对co模块的简单模拟 function run(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(); } function a(aa){ return new Promise(function (resolve, reject){ setTimeout(function (){ console.log(aa); resolve(‘dataA‘); }, 1000); }); } function b(bb){ return new Promise(function (resolve, reject){ setTimeout(function (){ console.log(bb); resolve(‘dataB‘); }, 1000); }); } function *gen(){ console.log(yield a(‘aa‘)); console.log(yield b(‘bb‘)); } run(gen); /* 等一秒 aa dataA 等一秒 bb dataB */
thunk方式:
// 对co模块的简单模拟 function run(fn) { var gen = fn(); function next(err, data) { var result = gen.next(data); if (result.done) return; result.value(next); } next(); } var Thunk = function(fn){ return function(...args){ return function(callback){ return fn.call(this, ...args, callback); }; }; }; function a(aa, cb){ setTimeout(function (){ console.log(aa); cb(null, ‘dataA‘); }, 1000); } function b(bb, cb){ setTimeout(function (){ console.log(bb); cb(null, ‘dataB‘); }, 1000); } var aThunk = Thunk(a); var bThunk = Thunk(b); function *gen(){ console.log(yield aThunk(‘aa‘)); console.log(yield bThunk(‘bb‘)); } run(gen); /* 等一秒 aa dataA 等一秒 bb dataB */
标签:模块 func thunk next bsp settime turn reject llb
原文地址:http://www.cnblogs.com/jyuf/p/7857405.html