Skip to content
Discussion options

You must be logged in to vote

Hey @shield178! 😊

I think I understand the issue you’re facing. You want to run multiple async tasks, but stop any remaining ones as soon as one fails. A good way to do this in Rust with Tokio is to use futures::future::select_all.

Here’s a simple example:

use futures::future::select_all;
use tokio::time::{sleep, Duration};
use tokio::task;

#[tokio::main]
async fn main() {
    let tasks: Vec<_> = vec![
        task::spawn(async { sleep(Duration::from_secs(3)).await; Ok::<_, &str>("A done") }),
        task::spawn(async { sleep(Duration::from_secs(1)).await; Err::<&str, _>("B failed") }),
        task::spawn(async { sleep(Duration::from_secs(2)).await; Ok::<_, &str>("C done") }),
    ];

…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by shield178
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Question Ask and answer questions about GitHub features and usage Programming Help Discussions around programming languages, open source and software development
3 participants