介绍
生成器函数是ES6提供的一种异步编程解决方案,语法行为与传统函数完全不同
function * gen{
yiwld '一只没有耳朵';
yiwld'一只没有尾巴'
}
生成器函数其实就是一个特殊的函数 异步编程
之前的都是纯回调函数进行异步
创建这个函数的方法
function * gen(){
}
function 后面加一个 星 号
声明 调用
yield是生成器函数代码的分隔符
使用next来执行输出,但只输出第一位
function *gen(){
console.log(11);
yield;
console.log(22);
yield;
console.log(33);
yield;
console.log(44);
}
let a =gen()
// 使用next来执行输出,但只输出第一位
a.next()
a.next()
// a.next()
// a.next()
这里只写了两个next所有只输出前两个
参数传递
function *ga(g){
console.log(g);
let one = yield 111;
console.log(one);
let tow = yield 222;
console.log(tow);
let three = yield 333;
console.log(three);
}
let b =ga('aaa');
console.log(b.next());
console.log(b.next('bbb'));
console.log(b.next('ccc'));
console.log(b.next('ddd'));
生成器函数声明与传递
这样不会回调地狱
function one (){
setTimeout(()=>{
console.log(111);
azz.next();
},1000)
}
function tow (){
setTimeout(()=>{
console.log(222);
azz.next();
},2000)
}
function three (){
setTimeout(()=>{
console.log(333);
azz.next();
},3000)
}
function*gen (){
yield one();
yield tow();
yield three();
}
let azz=gen()
azz.next();