#Calling An Async Function From Within A Non-Async Closure

3 messages · Page 1 of 1 (latest)

pine marlin
#

Let's say I'm using a WebviewWindowBuilder to spawn an extra window, and I want this window to do some action when the window navigates to a different URL.

Example:

#[tauri::command]
pub fn spawn_window(
    app: AppHandle
) -> Result<(), String> {
    WebviewWindowBuilder::new(
        &app,
        "some-label",
        WebviewUrl::External(some_url)
    )
    .title("some title")
    .on_navigation(|url| {
        let poll = some_async_func(url).await; // call some async code
        do_stuff(poll);
        true
    })
    .build()
    .map_err(|e| format!("Error: {}", e))?;
    Ok(())
}

The problem I run into is that in order to fetch this data from the async function call, it must be called from an async body as well, and closures do not support async. Passing in an async function to on_navigation is also not an option since 1) I might want to capture the environment of my spawn_window command through a closure and 2) it would return a Future when on_navigation requires something that returns a bool.

I've tried doing stuff like:

...
.on_navigation(|url| {
    Handle::current().spawn(async {
        let poll = some_async_func(url).await;
        do_stuff(poll);
    });
    true
})
...

But this will panic and the compiler says I have to call it from inside a Tokio runtime. I'm sort of new to async rust and I'm also out of ideas. Is there any way to run code asynchronously from this closure?

wispy mauve