rustasync / runtime

Empowering everyone to build asynchronous software
https://docs.rs/runtime
Apache License 2.0
862 stars 28 forks source link

How to call an async function from a normal function? #43

Closed ufosky closed 4 years ago

ufosky commented 5 years ago

I found if I use an async function, the other codes using this function must implement as an async function. Is there some suggestion for using async function from normal function?

zeroqn commented 5 years ago

Either use

futures::executor::block_on(your_future)

or

use runtime_tokio::Tokio;

fn main() {
    runtime::raw::enter(Tokio, your_future);
}

If you want to run it using this crate.

yoshuawuyts commented 5 years ago

We could / should probably expose some convenience methods here, so nobody ever needs to use runtime::raw directly:

with #[runtime::main]

runtime::task::block_on(async move {
    /* code goes here */
})

without #[runtime::main]

runtime_tokio::Tokio::block_on(async move {
    /* code goes here */
})
yoshuawuyts commented 5 years ago

Related: https://github.com/rustasync/runtime/issues/42