javascript - How to use the Generator function yield in es6?
PHP中文网
PHP中文网 2017-06-26 10:50:39
0
1
716

Look at the code first:

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!

How to understand this output result? After thinking for a long time, I couldn't understand the results of his operation.
There is also the following 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

I still don’t understand, please help me analyze the above two pieces of code and help me learn the Generator function. Thank you.

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(1)
刘奇

yield The keyword has two functions:

  1. Pauses generator function execution and returns the value of the following expression

  2. Resume the generator function execution and get the optional parameters passed in by the next method

The two examples you gave both use yield to receive the parameters passed in by the next method.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template