A 3rd-party API library provides an iterator for listing items and features built-in pagination. It's blocking and I would like to do multiple listing in parallel.
async def list_multiple(params_list):
async_tasks = []
for params in params_list:
async_tasks.append(list_one(**params))
await asyncio.gather(*async_tasks)
async def list_one(**kwargs):
blocking_iterator = some_library.get_api_list_iterator(**kwargs)
async for item in iterate_blocking(blocking_iterator):
pass # do things
async def iterate_blocking(iterator):
loop = asyncio.get_running_loop()
while True:
try:
yield await loop.run_in_executor(None, iterator.next)
except StopIteration:
break
But doing this raises
TypeError: StopIteration interacts badly with generators and cannot be raised into a Future
and blocks all threads. How do I iterate a blocking iterator correctly?