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.
怪我咯2017-06-26 10:52:39
yield
The keyword has two functions:
Pauses generator function execution and returns the value of the following expression
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.