Created
November 29, 2022 00:57
-
-
Save dgjustice/6e3dcfe639a7d05f9aea69f2dae7d011 to your computer and use it in GitHub Desktop.
Collect tokio tasks and process results
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use tokio; | |
fn main() { | |
// we want to use this after the async block | |
let hosts = ["hostA", "hostB"]; | |
let rt = tokio::runtime::Runtime::new().unwrap(); | |
let mut results = Vec::with_capacity(hosts.len()); | |
rt.block_on(async { | |
let mut handles = Vec::with_capacity(hosts.len()); | |
for host in hosts { | |
let cmd = "foobar".to_owned(); | |
handles.push(tokio::spawn(maybemaybe( | |
host.to_owned(), | |
"cli_show".to_string(), | |
cmd, | |
))); | |
} | |
for handle in handles { | |
results.push(handle.await.unwrap()); | |
} | |
}); | |
for result in results.iter() { | |
println!("{:?}", result); | |
} | |
// do moar stuffs with hosts | |
println!("{}", hosts.len()); | |
} | |
async fn maybemaybe( | |
host: String, | |
cmd: String, | |
fmt: String, | |
) -> Result<String, Box<dyn std::error::Error + Send + Sync>> { | |
Ok(format!("{}-{}-{}", host, cmd, fmt)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment