Locked learning resources

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

Unlock This Lesson

Locked learning resources

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

Unlock This Lesson

Reading a Live Feed With for await...of

Reading a Live Feed With for await…of

In this lesson, you port the live stream Priya’s dashboard reads as each reading arrives. In Python, ticks() is an async generator, an async def that yields. Before each reading it awaits. In the real service, that’s the wait for the sensor; here, asyncio.sleep(0) stands in, with no real delay.

Then main() loops with async for, and asyncio.run() starts the event loop:

Language: Python
import asyncio

async def ticks():
    for value in [12.5, 13.1]:
        await asyncio.sleep(0)
        yield value

async def main():
    async for t in ticks():
        print("tick", t)

asyncio.run(main())

It prints tick 12.5, then tick 13.1. JavaScript has async functions, and it has generators, so the question is whether one function can be both.

First, the wait. JavaScript’s awaitable is a promise, and Promise.resolve() hands you one that’s already fulfilled, here with no value. Awaiting it pauses the function only until JavaScript comes back to it: no timer, no network.

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

00:00 In this lesson, you’ll port the live stream Priya’s dashboard reads as readings arrive. In Python, ticks() is an async generator: an async def that yields.

00:12 Before each reading, it awaits the sensor. Here, asyncio.sleep(0) stands in, with no real delay. Then main() loops with async for, and asyncio.run() starts the event loop.

00:26 It prints two ticks, 12.5 and 13.1. JavaScript has async functions and generators: can one function be both?

00:39 First, the wait. JavaScript’s awaitable is a promise, and Promise.resolve() hands you one that’s already fulfilled, here with no value. Awaiting it pauses the function only until JavaScript comes back to it: no timer, no network.

00:56 Now the port. async def with a yield becomes async function*: the star from function*, with async in front.

01:05 The loop carries over as a for...of. await Promise.resolve() takes the place of asyncio.sleep(0): a real await, with no real wait.

01:16 And each reading is yielded, as in Python.

01:21 Python’s async for becomes for await, and the keyword moves: await goes after for. Watch out: Python’s word order, async for, doesn’t parse in JavaScript.

01:34 console.log() replaces print.

01:38 There’s no main() here, and no asyncio.run(). In Python, an async for outside an async function is a syntax error. So what does this file log?

01:50 Your turn: pause the video and predict.

01:58 It logs tick 12.5, then tick 13.1.

02:03 A module’s top level may await, and there’s no event loop to start: JavaScript runs it for you.

02:11 How does for await get its values? It calls the source’s Symbol.asyncIterator method, as Python’s async for calls __aiter__(), and gets an iterator.

02:23 It’s the protocol you wrote by hand, with one change: its .next() returns a promise, not the result itself. The loop awaits the promise and gets the same result object: a value and a done flag.

02:36 Then it asks again, until done is true. Here the analogy stops: awaiting Python’s __anext__() gives the bare value, and raises StopAsyncIteration at the end.

02:50 Awaiting JavaScript’s .next() always gives a result object.

02:55 An async generator has only this async hook, and no Symbol.iterator. Watch out: as in Python, a plain for...of, or a spread, over ticks() fails; reach for for await.

03:11 A generator writes this hook for you. This feed object writes it by hand: the shape you wrote for Symbol.iterator, made async. Its Symbol.asyncIterator method, bracketed since its name is a symbol, returns an object with an async .next().

03:26 It takes the readings array’s iterator, and each call hands on its next result, wrapped in a promise. The same loop logs both ticks.

03:37 The loop awaits each promise before asking again. Given an array, for await falls back to its ordinary iterator, awaiting each item; Python’s async for refuses a list.

03:50 Watch out: Python holds a failed task until you await it, but a started promise that fails while the loop waits on another goes unhandled, and Node exits; for one job at a time, start each in an async generator.

04:05 Sometimes the dashboard wants every reading at once. Python collects them with an async comprehension inside main(). JavaScript’s tool is Array.fromAsync(): it reads an async source to the end and builds an array.

04:20 It returns a promise as well, so you await it. It logs 12.5 and 13.1, the same list Python prints.

04:31 So Python’s async for becomes for await, and an async generator is an async function*. Both work through the Symbol.asyncIterator hook, whose .next() returns a promise for a value and a done flag.

04:46 As in Python, that’s how you expose paged or streamed data in JavaScript: an async generator, where the code that reads it decides how much to take. Next up is JavaScript Iterators and Generators for Pythonistas (Quiz).

05:01 There, you’ll recall iterators, generators and async iteration on fresh examples.

Become a Member to join the conversation.