Skip to content
jshacks.dev
Functions

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.

1 min read
Summarize in AI

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.

JavaScript
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'));
Text
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.

Taggednode 24
Share

More snippets

Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.