ES6 Generator 基本使用

Guanhui
發布: 2020-06-24 18:05:58
轉載
2208 人瀏覽過

ES6 Generator 基本使用

本文實例講述了ES6 Generator基本使用方法。分享給大家供大家參考,具體如下:

1.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是由functinon*定義的,在generator內部可以使用yield

  • Generator不是函數,而是一個對象,並且在執行開始就進入暫停狀態,而不是直接執行全部操作

  • 透過next()來執行下一步操作,返回的都是{ value: xxx, done: xxx }這樣的形式,value代表上一次操作傳回的值,done有兩個值,一個是true,一個是false,表示整個流程是否全部結束。

2.Generator非同步程式設計

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更適合。

3.yield和yield*

先來看兩段程式碼

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進行遍歷迭代。

推薦教學:《JS教學

以上是ES6 Generator 基本使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
es6
來源:jb51.net
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!