Skip to content

Instantly share code, notes, and snippets.

@MarcWang
Created March 8, 2016 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarcWang/ea108e4ea3d2e327e7f5 to your computer and use it in GitHub Desktop.
Save MarcWang/ea108e4ea3d2e327e7f5 to your computer and use it in GitHub Desktop.

ES6 - 生成器 (Generators)

Generator的幾個重要規則

  • 函數執行到yield時會先暫停,並返回呼叫函數處繼續執行
  • 要呼叫暫停以下的程式時,需要呼叫next方法
  • 函數宣告方式必須加星號*function()
function* gen(firstValue) {
    console.log('call first');
    var secondValue = yield `input first value ${firstValue}`;
    console.log('call second');
    yield `input second value ${secondValue}`;
    if (secondValue == 'yes') {
        yield `yes`;
    } else {
        yield `no`;
    }
}


var iter = gen("hello");
console.log(iter.next().value); //input first value hello
console.log(iter.next('yes').value); //input second value yes
console.log(iter.next().value); //yes
console.log(iter.next().done); //true

呼叫此函數,並回傳一個Generator物件。此時還沒執行函數中任何一行程式,所以你並不會看到call first的log。

var iter = gen("hello");

呼叫Generator物件的next()方法,此時函數開始執行,所以你會看到顯示call first,執行遇到第一個yield時,暫停並返回,返回的物件{value: 'input first value hello', done: false}

console.log(iter.next().value); //input first value hello

再次呼叫Generator物件的next()方法,並帶入參數yes,會繼續上次暫停執行的那一行,並將參數值給secondValue繼續執行,一樣執行到下一個yield時,暫停並返回物件{value: 'input second value yes', done: false}

console.log(iter.next('yes').value); //input second value yes

判斷使否結束是依據返回物件中的done值,true表示已結束,反之,尚可繼續執行。

console.log(iter.next().value); //yes
console.log(iter.next().done); //true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment