Hi, I want to run an async function within a trait method that I implement. Since we know that async functions cannot be run inside regular functions in Rust, and the trait methods I need to implement are regular functions, is there a way to handle this?
If you are running your code outside of the context of an asynchronous runtime, you could use a light-weight executor like pollster
or futures::executor
.
If you need this to be compatible with the tokio
runtime, then tokio
uses Handle
for this:
In your trait function, or in a field of your struct that implements the trait, take a Handle
, and then call handle.block_on(async_call())
.
A Handle
should be created by the caller while they are in an async
function ran by tokio
.
Note that in tokio
, block_on
can only be called in non-async code. An async function can't call your trait method and then have it run block_on
.
If you can change the definition of the trait, you can return Box<dyn Future>
from a trait method, or use #[async_trait]
.
amazing. its work. thanks alot for your help
thanks all for your help