-
Notifications
You must be signed in to change notification settings - Fork 1
Async and Future
The plan was actually to just simply change every request related method to async,
but once it's done, it means that the users should code in async way too,
which may cause troubles for those who already using my package in their code and also may be unfriendly to some Pythoners.
So I decided to separate them by creating a thread to run event loop, and the async functions will be wrapped with Workflow
to be submitted to that loop.
For more detail, please see CoroutineLoop.py
please be aware, provide wait=False
to that method is required if you want a Future to be returned since every wait
is defaulted to True
Like ES6 Promise, asyncio.run_coroutine_threadsafe
returns an object called Future
.
You can check whether the submitted task is done by running future.done()
.
Task done successfully, future.result()
will give you the result async funtion returns.
Task met some error, running future.result()
won't give you the result but raises that Exception, but it can be avoided by calling err = future.exception()
to check if there is an Exception raised, then decide what is the next step.
Example:
'''delete a conversation'''
rm_fut = bot.removeConversation(conversation_id=conversation_id, wait=False)
'''create a new conversation'''
cr_fut = bot.createConversation(wait=False)
while not rm_fut.done():
time.sleep(0.1)
if rm_fut.exception():
raise rm_fut.exception()
while not cr_fut.done():
time.sleep(0.1)
if cr_fut.exception():
raise cr_fut.exception()
else:
res = cr_fut.result()
print("conversation_id:",res)
Feel free to ask any questions or share me with your thoughts!