搜尋

首頁  >  問答  >  主體

javascript - es6中Generator函數yield怎麼使用?

先看下程式碼:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<code>function wrapper(generatorFunction) {

    return function (...args) {

        let generatorObject = generatorFunction(...args);

        generatorObject.next();

        return generatorObject;

    };

}

 

const wrapped = wrapper(function* () {

    console.log(`First input: ${yield}`);

    return 'DONE';

});

 

wrapped().next('hello!')

// First input: hello!</code>

這個輸出結果怎麼理解呢?想了半天不理解他的運行結果。
還有下面程式碼:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<code>function* dataConsumer() {

  console.log('Started');

  console.log(`1. ${yield}`);

  console.log(`2. ${yield}`);

  return 'result';

}

 

let genObj = dataConsumer();

genObj.next();

// Started

genObj.next('a')

// 1. a

genObj.next('b')

// 2. b</code>

還是看不懂,請大神幫忙分析上述兩段程式碼,幫我學習Generator函數。謝謝了。

PHP中文网PHP中文网2833 天前764

全部回覆(1)我來回復

  • 怪我咯

    怪我咯2017-06-26 10:52:39

    yield 關鍵字有兩個作用:

    1. 暫停產生器函數執行並傳回後方表達式的值

    2. 恢復生成器函數執行並得到 next 方法傳入的選用參數

    你給到的兩個例子都是用 yield 接收了 next 方法傳入的參數。

    回覆
    0
  • 取消回覆