本文实例讲述了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进行遍历迭代。
感兴趣的朋友可以使用在线html/css/javascript代码运行工具:测试上述代码运行效果。
如对本文有疑问, 点击进行留言回复!!
JavaScript 好题汇总分享(持续更新,看到好题就写)
XMLHttpRequest 2级 &&进度事件&&JSONP
使用递归原生实现拷贝&&最简单的方法实现深拷贝
网友评论