Python uses the Future object to return sample code asynchronously, pythonfuture
Preface
This article describes how to use a Future object to return results asynchronously in python. I will share the content for your reference. I will not talk about it here. Let's take a look at the details.
A Future is used to indicate the results to be completed in the Future. asynchronous loops can automatically trigger the state of such objects.
Example:
import asyncio def mark_done(future, result): print('setting future result to {!r}'.format(result)) future.set_result(result) event_loop = asyncio.get_event_loop() try: all_done = asyncio.Future() print('scheduling mark_done') event_loop.call_soon(mark_done, all_done, 'the result') print('entering event loop') result = event_loop.run_until_complete(all_done) print('returned result: {!r}'.format(result)) finally: print('closing event loop') event_loop.close() print('future result: {!r}'.format(all_done.result()))
The output result is as follows:
scheduling mark_doneentering event loopsetting future result to 'the result'returned result: 'the result'closing event loopfuture result: 'the result'
In this example, the return statement is not called, but a result can be returned. The use of Future is the same as that of coroutine.
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.