Skip to content

Instantly share code, notes, and snippets.

@dgjustice
Created November 29, 2022 00:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgjustice/6e3dcfe639a7d05f9aea69f2dae7d011 to your computer and use it in GitHub Desktop.
Save dgjustice/6e3dcfe639a7d05f9aea69f2dae7d011 to your computer and use it in GitHub Desktop.
Collect tokio tasks and process results
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