I recommend calling async() to convert each coroutine to a task. Then call
wait() with the tasks. You can then compare the returned task(s) directly
to the input tasks. I.e.:
ws_task = asyncio.async(websocket.recv())
redis_task = asyncio.async(redis_subscriber.next_published())
done, pending = yield from asyncio.wait([ws_task, redis_task],
return_when=asyncio.FIRST_COMPLETED)
for task in done:
if task == ws_task:
yield from send_to_redis(task.result())
elif task == redis_task:
yield from send_to_websocket(task.result())
On Tue, Nov 11, 2014 at 3:52 PM, Don Spaulding <[email protected]>
wrote:
> Hi All,
>
> I'm trying to figure out The Right Way to wait on an asynchronous result
> from two different asyncio-enabled libraries. At first glance (and my
> first implementation of a solution to my problem), it seems like I want to
> use something like the following:
>
> # given a server that shuttles messages between a websocket and a
> redis server
> # wait until the next message arrives, from whichever source, and send
> it to the other
> ws_coro = websocket.recv()
> redis_coro = redis_subscriber.next_published()
> done, pending = yield from asyncio.wait([ws_coro, redis_coro],
> return_when=asyncio.FIRST_COMPLETED)
> for task in done:
> if task._coro == ws_coro:
> yield from send_to_redis(task.result())
> elif task._coro == redis_coro:
> yield from send_to_websocket(task.result())
>
> Indeed, this works, except that the behavior that comes after
> asyncio.wait() seems a little suspect to me. To differentiate between the
> returned result, I have to use the private attribute `task._coro`. Is that
> really the intended use of asyncio.wait? Is there something more
> appropriate to my situation?
>
> To recap, I want to wait on the first completed task of two (or more)
> heterogenous task types. And then I want to process results from each task
> type in a distinct way.
>
> I'd gladly welcome any advice on the topic.
> --
> Don
>
--
--Guido van Rossum (python.org/~guido)