Sending Values Into a Generator

Priya’s feed now hands out its readings from a function*, one value per yield. The dashboard also needs data to travel the other way. Its display panel is a Python generator that waits for the service to push in each new reading with send().

JavaScript generators have no send() method. In this lesson, you’ll find out what replaces it, why a reading can vanish without an error, and how to shut a generator down cleanly.

Push a Reading in With next(value)

In the Python service, the display panel is a generator that pauses at a bare yield and prints whatever arrives there. The service starts it with next(), then sends it a reading:

Language: Python
def listener():
    while True:
        reading = yield
        print("got", reading)

display = listener()
next(display)
display.send(13.1)

That prints got 13.1. Python won’t let you send a value other than None to a generator that hasn’t started. Calling display.send(12.5) before priming it with next(display) or display.send(None) raises TypeError: can't send non-None value to a just-started generator.

JavaScript folds Python’s next() and send() calls into one method. A generator’s .next() takes an optional argument, and that argument becomes the value of the yield expression where the generator is paused. So display.next(13.1) plays the part of Python’s display.send(13.1), and a bare display.next() plays the part of next(display).

Unlike Python’s send(), JavaScript’s .next() returns an iterator result object such as { value: undefined, done: false }, not the yielded value on its own. A bare .next() hands the paused yield undefined, not None.

Now suppose the port leaves out the priming call, a slip Python would catch with that TypeError. Will JavaScript catch it too? As in Python’s while True:, a while (true) loop runs until something stops it:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.