本文摘自PHP中文网,作者Guanhui,侵删。

本文实例讲述了ES6 Generator基本使用方法。分享给大家供大家参考,具体如下:
1.Generator介绍
先来一段Generator的基础代码
1 2 3 4 5 6 7 8 9 10 11 | function * g(){
yield 100;
yield 200;
return 300;
}
let gg = g();
console.log(gg);
console.log(gg.next());
console.log(gg.next());
console.log(gg.next());
console.log(gg.next());
|
首先我们看到:
Generator是由functinon*定义的,在generator内部可以使用yield
Generator不是函数,而是一个对象,并且在执行开始就进入暂停状态,而不是直接执行全部操作
通过next()来执行下一步操作,返回的都是{ value: xxx, done: xxx }这样的形式,value代表上一次操作返回的值,done有两个值,一个是true,一个是false,表示整个流程是否全部结束。
2.Generator异步编程
generator是ES6中引入的异步解决方案,我们来看看它与promise处理异步的对比,来看它们的差异。
1 2 3 4 5 6 7 8 9 10 | function asyncFunc(data) {
return new Promise( resolve => {
setTimeout(
function () {
resolve(data)
},1000
)
})
}
|
promise的处理方式:
1 2 3 4 5 6 7 8 9 | asyncFunc( "abc" ).then( res => {
console.log(res);
return asyncFunc( "def" )
}).then( res => {
console.log(res);
return asyncFunc( "ghi" )
}).then( res => {
console.log(res);
})
|
generator的处理方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | function * g() {
const r1 = yield asyncFunc( "abc" );
console.log(r1);
const r2 = yield asyncFunc( "def" );
console.log(r2);
const r3 = yield asyncFunc( "ghi" );
console.log(r3);
}
let gg = g();
let r1 = gg.next();
r1.value.then(res => {
let r2 = gg.next(res);
r2.value.then(res => {
let r3 = gg.next(res);
r3.value.then(res => {
gg.next(res)
})
})
})
|
promise多次回调显得比较复杂,代码也不够简洁,generator在异步处理上看似同步的代码,实际是异步的操作,唯一就是在处理上会相对复杂,如果只进行一次异步操作,generator更合适。
3.yield和yield*
先来看两段代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | function * g1() {
yield 100;
yield g2();
return 400;
}
function * g2() {
yield 200;
yield 300;
}
let gg = g1();
console.log(gg.next());
console.log(gg.next());
console.log(gg.next());
console.log(gg.next());
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | function * g1() {
yield 100;
yield* g2();
return 400;
}
function * g2() {
yield 200;
yield 300;
}
let gg = g1();
console.log(gg.next());
console.log(gg.next());
console.log(gg.next());
console.log(gg.next());
|
yield对另一个generator不会进行遍历,返回的是迭代器对象,而yield*会对generator进行遍历迭代。
推荐教程:《JS教程》
以上就是ES6 Generator 基本使用的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
聊聊javascript中eval()函数的用法
ES6之promise的学习
10个实用的ES6方法,快来收藏!
深入学习ES6作用域
浅谈ES6中的字符串(代码示例)
ES6中symbol的详细介绍(代码示例)
javascript中amd和ES6模块导入导出的比较(代码示例)
javascript普通函数和箭头函数有什么区别?
ES6中变量的解构赋值的用法介绍(附代码)
了解ES6中数组去重的两种方式
更多相关阅读请进入《ES6》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » ES6 Generator 基本使用