生成器函数也是一种异步编程的解决方案,与普通函数不同的是函数名前有*,通过yield将函数体分成多个区域,且是通过.next()调用的
function *show() {console.log('第一个代码块');yield '1';console.log('第二个代码块');yield '2';console.log('第三个代码块');yield '3';console.log('第四个代码块');
}
const iterator = show();
iterator.next(); // 执行第一个代码块
iterator.next(); // 执行第二个代码块
iterator.next(); // 执行第三个代码块
iterator.next(); // 执行第四个代码块
适用场景:等到某段代码执行完之后才执行另一段代码的时候
next方法可传递参数(next参数将作为上一个yield的返回结果)
function *show() {console.log('第一个代码块');const result1 = yield '1';console.log(result1);console.log('第二个代码块');const result2 = yield '2';console.log(result2);console.log('第三个代码块');const result3 = yield '3';console.log(result3);console.log('第四个代码块');
}
const iterator = show();
iterator.next(); // 执行第一个代码块
iterator.next('参数1'); // 执行第二个代码块
iterator.next('参数2'); // 执行第三个代码块
iterator.next('参数3'); // 执行第四个代码块
案例:1s后输出hello,2s后输出world,3s后输出aaa
function hello() {setTimeout(() => {console.log('hello');iterator.next();}, 1000);
}
function world() {setTimeout(() => {console.log('world');iterator.next();}, 2000);
}
function aaa() {setTimeout(() => {console.log('aaa');iterator.next();}, 3000);
}
function *show() {yield hello();yield world();yield aaa();
}
const iterator = show();
iterator.next();
上一篇:这些JS工具函数助力高效开发