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:
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.