#!/usr/bin/env python3 import asyncio import random async def fetch_aio(i): await asyncio.sleep(random.randint(1, 5) / 5.0) return {'aio_arg': str(i)} def aio_map(coro, iterable, loop=None): if loop is None: loop = asyncio.get_event_loop() async def wrapped_coro(coro, value): return await coro(value) coroutines = (wrapped_coro(coro, v) for v in iterable) coros = asyncio.gather(*coroutines, return_exceptions=True, loop=loop) if not loop.is_running(): loop.run_until_complete(coros) else: # problem starts here # If we run loop.run_until_complete(coros) as well, # we get 'RuntimeError: Event loop is running.' asyncio.wait(coros) # But this way, we get 'asyncio.futures.InvalidStateError: Result is not ready.' return coros.result() def run_aio_map_fron_non_async(): results = list(aio_map(fetch_aio, range(5))) assert(results == [{'aio_arg': '0'}, {'aio_arg': '1'}, {'aio_arg': '2'}, {'aio_arg': '3'}, {'aio_arg': '4'}]), results print('Assert ok!') async def main_loop(loop): results = list(aio_map(fetch_aio, range(5))) assert(results == [{'aio_arg': '0'}, {'aio_arg': '1'}, {'aio_arg': '2'}, {'aio_arg': '3'}, {'aio_arg': '4'}]), results print('Assert ok!') def run_aio_map_fron_async(): loop = asyncio.get_event_loop() close_after_run = not loop.is_running() loop.run_until_complete(main_loop(loop)) if close_after_run: loop.close() if __name__ == '__main__': print('run_aio_map_fron_non_async:') run_aio_map_fron_non_async() print('run_aio_map_fron_async:') run_aio_map_fron_async() print('done.')