Skip to content

How to retry an async func which has params? #83

Answered by Xuanwo
Zrs000 asked this question in Q&A
Discussion options

You must be logged in to vote

Sadly, we don't have direct support for async func which has params (due to the limit of rust itself). The only possible way is to capture as a closure:

use anyhow::Result;
use backon::ExponentialBuilder;
use backon::Retryable;

async fn fetch(url: &str) -> Result<String> {
    Ok(reqwest::get(url).await?.text().await?)
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
    let content = (|| async { fetch("https://www.rust-lang.org").await })
        .retry(&ExponentialBuilder::default())
        .when(|e| e.to_string() == "retryable")
        .await?;

    println!("fetch succeeded: {}", content);
    Ok(())
}

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by Xuanwo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants