4 ms·
> The virality of async await is that once you mark a function async, then you can only call it from another async function Rust calling async function in non-
by tcfhgj 1y ago
> The virality of async await is that once you mark a function async, then you can only call it from another async function
Rust calling async function in non-async function:
...
// Create the runtime
let rt = Runtime::new().unwrap();
// Get a handle from this runtime
let handle = rt.handle();
// Execute the future, blocking the current thread until completion
handle.block_on(async {
println!("hello");
});
https://docs.rs/tokio/latest/tokio/runtime/struct.Handle.html#method.block_on https://docs.rs/tokio/latest/tokio/runtime/struct.Handle.htm...
- vlovich123 1y agoOf course, spinning up a new runtime within the context of a boundary like that is probably wasteful (lots of new threads created if you’re not careful). But you could stash that runtime behind a OnceLock (you’d need to block_on the Handle I imagine rather than the Runtime directly, but doable). And calling blocking from non-blocking: let result = tokio::task::spawn_blocking(|| { 5 }).await; This of course is basically essentially what Zig is doing, except instead of hidden global state it’s parameter passed. This is one area Zig does do better in - I wish Rust would default more to instance state instead of implicit global state.
- Dylan16807 1y agoSo that's an escape in Rust and tokio. But consider a language that doesn't have block_on, like javascript.