#Rust Reqwest fire and forget

12 messages · Page 1 of 1 (latest)

slender root
#

I have async function where I would like to fire a request and not care about the response for it.

I was wondering if creating a request and not using await would work ?

#[tokio::main]
async fn main() {
    reqwest::get("http://example.com");  // Missing await!
    println!("Request sent, moving on...");
}
slender root
#

It doesnot work actually I tested it out.
LLM suggested this, but still does not work

#[tokio::main]
async fn main() {
    tokio::spawn(async {
        let _ = reqwest::get("http://example.com").await;
    });

    println!("Request sent, moving on...");
    
    // Keep the runtime alive long enough
    tokio::time::sleep(std::time::Duration::from_secs(1)).await;
}
chilly adder
#

Might be of interest but if you want to fire and forget why do this in the first place. If you end up waiting for the task to finish anyway is it much different than just an await?

#

tokio::spawn returns a handle to the task which you can await. Instead of the sleep just store the handle in a variable and call await on it instead of sleeping.

chilly adder
#

For example this does the same but instead of waiting one second which doesnt guarantee the task will be completed, it just stores the handle waits until the task is completed before exiting.

#

That said I don't recommend using LLM's as they often cause more confusion than help when learning. tokio's documentation is pretty good so you are better off reading that instead.

sudden hollow
#

Yeah I wouldn't trust llms with async rust tbh 😅

slender root
#

I setup something like this and I get this flow, I would like to not care about the second request at all.

#[tokio::main]
async fn main() -> Result<()> {
    let _ = fire_and_forget().await;
    println!("Running other Task");
    println!("Final Task");
    Ok(())
}

async fn fire_and_forget() -> Result<()> {
    println!("starting request 1");
    let _ = reqwest::get("http://localhost:8000").await;
    println!("ending request 1");

    println!("Starting request 2");

    let h = tokio::spawn(async {
        let _ = reqwest::get("http://localhost:8000").await;
        println!("ending request 2");
    });

    let _ = h.await;
    Ok(())
}
#

The real world usecase is that Im trying to run a middleware, where I would like to call to extend session of the user (which is not critical that it needs to work). I would like it to be like the beacon api from js