search

Home  >  Q&A  >  body text

javascript - How to use the Generator function yield in es6?

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中文网2697 days ago678

reply all(1)I'll reply

  • 怪我咯

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

    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.

    reply
    0
  • Cancelreply