簡單的co用例:javascript
var co=require("co") class view{ constructor(){ co(function*(){ var p1=this.ajax1() var p2=this.ajax2() try{ var result=yield [p1,p2] console.log(result) }catch (err){ console.info(err) } }.bind(this)) } ajax1(){ return new Promise(function(res,rej){ var t=1 setTimeout(function(){ t=t+1 res(t) },2000) }) } ajax2(){ return new Promise(function(res,rej){ var t="this is the t2 errone" setTimeout(function(){ rej(t) },200) }) } } module.exports=view
co ajaxjava
var co=require("co") class view{ constructor(){ co(function*(){ var p1=this.ajax1() var p2=this.ajax2() try{ var result=yield [p1,p2] console.log(result) }catch (err){ console.info(err) } var p3=yield this.ajax3() console.log(p3) }.bind(this)) } ajax1(){ return $.ajax({ url: '/rulecycle/test1.json', data: {naem:21}, type:"get" })// yield 必須是promise 或者thunk函數,jquery ajax 1.7版本後自己會返回promise對象,不須要手動封裝 } ajax2(){ return $.ajax({ url: '/rulecycle/test1.json', data: {naem:21}, type:"get" }) } ajax3(){ return $.ajax({ url: '/rulecycle/test1.json', data: {naem:21}, type:"get" }) } } module.exports=view
es6 async,適用簡單的異步邏輯 :jquery
class view{ constructor(){ this.ajax1() } async ajax1(){ try { var resultData = await $.ajax({ url: '/rulecycle/test1.json', type:"get" }) console.info(resultData) }catch (e){ console.info(e) } } } module.exports=view
附註 : babel 默認不支持generator,async特性, 須要在webpack入口文件引入webpack
require("babel-polyfill");