直接贴代码
JavaScript
var request = require('request'); function* main() { var result = yield get("http://www.baidu.com/"); console.log('request success'); } function get(url){ request(url, function(error, response, body){ it.next(response); }); } var it = main(); it.next(); console.log('normal log');
varrequest=require('request'); function*main(){ varresult=yieldget("http://www.baidu.com/"); console.log('request success'); } functionget(url){ request(url,function(error,response,body){ it.next(response); }); } varit=main(); it.next(); console.log('normal log');
贴个结果
嗯,结果有点超乎我的意料,我以为Generator函数这么特别,会卡住流程。
这样有没有Generator感觉都是一样的,只不过把异步的包在一个函数里面,对外没有暴露出来而已
JavaScript
function main(){ return { next: function(){ get("http://www.oa.com/"); function get(url){ request(url, function(error, response, body){ cb(response); }); } function cb (resp){ console.log('request success'); } } } } var it = main(); it.next(); console.log('normal log');
functionmain(){ return{ next:function(){ get("http://www.oa.com/"); functionget(url){ request(url,function(error,response,body){ cb(response); }); } functioncb(resp){ console.log('request success'); } } } } varit=main(); it.next(); console.log('normal log');
嗯,一次失败的研究,继续找找其他应用场景。