您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章主要讲解了ES6中Generator基本使用方法的实例解析,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。
本文实例讲述了ES6 Generator基本使用方法。分享给大家供大家参考,具体如下:
先来一段Generator的基础代码
function* g(){
yield 100;
yield 200;
return 300;
}
let gg = g();
console.log(gg); // Object [Generator] {}
console.log(gg.next()); // { value: 100, done: false }
console.log(gg.next()); // { value: 200, done: false }
console.log(gg.next()); // { value: 300, done: true }
console.log(gg.next()); // { value: undefined, done: true }首先我们看到:
generator是ES6中引入的异步解决方案,我们来看看它与promise处理异步的对比,来看它们的差异。
// 这里模拟了一个异步操作
function asyncFunc(data) {
return new Promise( resolve => {
setTimeout(
function() {
resolve(data)
},1000
)
})
}promise的处理方式:
asyncFunc("abc").then( res => {
console.log(res); // "abc"
return asyncFunc("def")
}).then( res => {
console.log(res); // "def"
return asyncFunc("ghi")
}).then( res => {
console.log(res); // "ghi"
})generator的处理方式:
function* g() {
const r1 = yield asyncFunc("abc");
console.log(r1); // "abc"
const r2 = yield asyncFunc("def");
console.log(r2); // "def"
const r3 = yield asyncFunc("ghi");
console.log(r3); // "ghi"
}
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更合适。
先来看两段代码
function* g1() {
yield 100;
yield g2();
return 400;
}
function* g2() {
yield 200;
yield 300;
}
let gg = g1();
console.log(gg.next()); // { value: 100, done: false }
console.log(gg.next()); // { value: Object [Generator] {}, done: false }
console.log(gg.next()); // { value: 400, done: true }
console.log(gg.next()); // { value: undefined, done: true }function* g1() {
yield 100;
yield* g2();
return 400;
}
function* g2() {
yield 200;
yield 300;
}
let gg = g1();
console.log(gg.next()); // { value: 100, done: false }
console.log(gg.next()); // { value: 200, done: false }
console.log(gg.next()); // { value: 300, done: false }
console.log(gg.next()); // { value: 400, done: true }yield对另一个generator不会进行遍历,返回的是迭代器对象,而yield*会对generator进行遍历迭代。
看完上述内容,是不是对ES6中Generator基本使用方法的实例解析有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。