generator介绍
es6为异步编程提供解决方案,通过yeild关键字,把函数的执行流程挂载起来,为改变执行流程提供可能。
generator组成及用法
Generator两点区分普通函数
- function 后带*
- 函数内部有yield表达式
用法:
//generator函数的声明
function* gen(){
console.log(111)
var g1=yield 1;
console.log('g1:',g1)//g1: 参数一
var g2=yield 2;
console.log('g2:',g2)//g2: 参数二
var g3=yield 3;
console.log('g3:',g3)//g3: 参数三
return g1+g2+g3
}
const g=gen() //不会立即执行
console.log(g)
const g1=g.next()
console.log(g1) //{{value: 1, done: false}}
const g2=g.next('参数一')
console.log(g2) //{value: 2, done: false}
const g3=g.next('参数二')
console.log(g3) //{value: 3, done: false}
const g4=g.next('参数三')
console.log(g4) //{value: "参数一参数二参数三", done: true}
好处
将异步回调代码编程类似于同步的形式代码。
// 之前代码格式
ajax("http://url-1",data1,function(err,result){
if(err){
return handle(err)
}
ajax("http://url-2",data2,function(err,result){
if(err){
return handle(err)
}
ajax("http://url-3",data3,function(err,result){
if(err) return handle(err)
return success(result);
})
})
})
//修改后
try{
let r1=yield ajax("http://url-1",data1)
let r2=yield ajax("http://url-2",data2)
let r3=yield ajax("http://url-3",data3)
success(r3)
}catch(err){
handle(err)
}
// 异步函数及调用方法
function ajax(url){
//请求函数
}
function * main(){
const users=yield ajax("http://ajax1")
const posts=yield ajax("http://ajax2")
const urls=yield ajax("http://ajax3")
}
const g=main()
//调用
function handle(result){
if(result.done){ return}
result.value.then(data=>{
handle(g.next(data))
})
}
handle(g.next())
function co(main){
const g=main()
function handle(result){
if(result.done){ return}
result.value.then(data=>{
handle(g.next(data))
})
}
handle(g.next())
}
co(main)