您好,登錄后才能下訂單哦!
這篇文章主要講解了ES6中Generator基本使用方法的實(shí)例解析,內(nèi)容清晰明了,對(duì)此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。
本文實(shí)例講述了ES6 Generator基本使用方法。分享給大家供大家參考,具體如下:
先來(lái)一段Generator的基礎(chǔ)代碼
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中引入的異步解決方案,我們來(lái)看看它與promise處理異步的對(duì)比,來(lái)看它們的差異。
// 這里模擬了一個(gè)異步操作 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多次回調(diào)顯得比較復(fù)雜,代碼也不夠簡(jiǎn)潔,generator在異步處理上看似同步的代碼,實(shí)際是異步的操作,唯一就是在處理上會(huì)相對(duì)復(fù)雜,如果只進(jìn)行一次異步操作,generator更合適。
先來(lái)看兩段代碼
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對(duì)另一個(gè)generator不會(huì)進(jìn)行遍歷,返回的是迭代器對(duì)象,而yield*會(huì)對(duì)generator進(jìn)行遍歷迭代。
看完上述內(nèi)容,是不是對(duì)ES6中Generator基本使用方法的實(shí)例解析有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。