Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over an asynchronous iterator with a timeout?

I think it's easier to understand in terms of code:

try:
    async for item in timeout(something(), timeout=60):
        await do_something_useful(item)
except asyncio.futures.TimeoutError:
    await refresh()

I want the async for to run at most 60 seconds.

like image 819
amirouche Avatar asked May 08 '18 20:05

amirouche


People also ask

How do I iterate through async generator?

The syntax is simple: prepend function* with async . That makes the generator asynchronous. And then use for await (...) to iterate over it, like this: async function* generateSequence(start, end) { for (let i = start; i <= end; i++) { // Wow, can use await!

What allows you to sequentially access Datafrom asynchronous data source?

ES6 introduced the iterator interface that allows you to access data sequentially. The iterator is well-suited for accessing the synchronous data sources like arrays, sets, and maps.

What is an AsyncGenerator?

The AsyncGenerator object is returned by an async generator function and it conforms to both the async iterable protocol and the async iterator protocol. Async generator methods always yield Promise objects.

What is Asynciterableiterator?

asyncIterator. The Symbol. asyncIterator well-known symbol specifies the default async iterator for an object. If this property is set on an object, it is an async iterable and can be used in a for await...of loop.


1 Answers

I needed to do something like this to create a websocket(also an async iterator) which times out if it doesn't get a message after a certain duration. I settled on the following:

socket_iter = socket.__aiter__()
try:
    while True:
        message = await asyncio.wait_for(
            socket_iter.__anext__(),
            timeout=10
        )
except asyncio.futures.TimeoutError:
    # streaming is completed
    pass
like image 102
Adverbly Avatar answered Sep 24 '22 13:09

Adverbly