Function run_async

Source
pub fn run_async<F: Future + Send>(f: F) -> Result<F::Output>
where F::Output: Send,
Expand description

A helper function to run an asynchronous task in a sync context.

If we are in a sync context, we can’t use any async functions without creating a new async runtime. Although it is possible to get a handle to an existing runtime using tokio::runtime::Handle::try_current, we can’t actually use it to run a sync function. Specifically, if we do:

if let Ok(rt) = tokio::runtime::Handle::try_current() {
    Ok(rt.block_on(f))
}

then Tokio will panic:

thread 'tests::verify' panicked at 'Cannot start a runtime from within a runtime. This happens because a function (like `block_on`) attempted to block the current thread while the thread is being used to drive asynchronous tasks.', backend/src/utils.rs:97:15

Instead, we check if there is an async runtime, if not, then we create an async runtime using Tokio, run the async function, and return. If there is an async runtime, we start a new thread, create a new runtime there, and execute the function using that runtime.