-
Notifications
You must be signed in to change notification settings - Fork 1
Async and Future
The plan was actually to just change every request-related method to async,
but once it's done, it means that the users should code in the async way too,
which may cause troubles for those who already implemented my package into their code and may be unfriendly to use for some Pythoners.
And that's why I decided to separate them by running a event loop in a new thread, the async functions will be wrapped with Workflow
to be submitted and run in that loop.
For more detail, please see CoroutineLoop.py
Be aware that provide wait=False
to that method is necessary if you want a Future to be returned since wait
in every function is defaulted to True
Very much similar to 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 gives you the result async funtion returns.
Task met some error, running future.result()
won't give you the result but raises that Exception, this 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!