Reputation: 406
I am trying to implement asyncio in a previously working program but my functions are returning coroutines instead of the objects I expect.
Example:
async def requester(things):
async def adder(item):
output = {}
output['timestamp'] = datetime.datetime.now().timestamp()
output['key'] = item
return output
to_insert = []
for thing in things:
to_insert.append(adder(thing))
mongodbcollection.insert_many(to_insert) # This throws the error
loop = asyncio.get_event_loop()
loop.run_until_complete(requester(['a', 'b', 'c']))
In this example, instead of objects being returned from the adder function, coroutines are returned, and naturally when I try to insert them into a database it throws TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping
. There are other asynchronous things happening in each of these functions, that is why they are async. How can I get this internal function to return the object as intended?
Upvotes: 0
Views: 3605
Reputation: 39636
You should use await
to execute a coroutine and get a result of the execution:
to_insert = []
for thing in things:
res = await adder(thing)
to_insert.append(res)
There's also a chance insert_many
should also be awaited if it's a coroutine.
Upvotes: 2