简单的co用例:
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 ajax
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,适用简单的异步逻辑 :
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入口文件引入
require("babel-polyfill");