Pass values into a generator with next
Pass values into a JavaScript generator with next, where the argument becomes the result of the paused yield expression. Works in any Node.js.
A generator is not only a producer. The value given to next(value) becomes the result of the yield the generator is paused on, which makes two-way conversations possible.
function* conversation() {
const name = yield 'Name?';
const language = yield `Hi ${name}, language?`;
return `${name} likes ${language}`;
}
const chat = conversation();
console.log(chat.next().value);
console.log(chat.next('Ada').value);
console.log(chat.next('JS'));Name?
Hi Ada, language?
{ value: 'Ada likes JS', done: true }The first next() runs to the first yield, and any argument to it is thrown away, because no yield is waiting yet. The second call answers the first question, the third answers the second, and the return ends the generator with done: true. See Generator.prototype.next.
This is the mechanism behind coroutine libraries that drove async code before async and await. For most code today, async functions say the same thing more clearly, so use two-way generators for parsers and state machines.