How correctly bind the sending time of each request:
(to correlate the time of a request with its response)
Cargo.toml
[dependencies]
# https://crates.io/crates/reqwest
reqwest = { version = "0.13", features = ["json"] }
tokio = { version = "1", features = ["full"] }
# https://crates.io/crates/chrono
chrono = "0.4.43"
# https://crates.io/crates/futures
futures = "0.3.31"
use futures::{stream, StreamExt};
use reqwest::Client;
use tokio;
use chrono::NaiveDateTime;
use chrono::Utc;
const CONCURRENT_REQUESTS: usize = 10;
#[tokio::main]
async fn main() {
let client = Client::new();
let urls = vec!["https://api.ipify.org"; 10];
let mut data = Vec::with_capacity(urls.len());
let mut tm_quer: Vec<NaiveDateTime> = Vec::with_capacity(urls.len());
let mut tm_resp: Vec<NaiveDateTime> = Vec::with_capacity(urls.len());
let bodies = stream::iter(urls)
.map(|url| {
let client = &client;
async move {
let resp = client.get(url).send().await?;
resp.bytes().await
}
})
.buffer_unordered(CONCURRENT_REQUESTS);
// ^^^_ tm_quer.push(Utc::now().naive_utc());
bodies
.for_each(|b| {
match b {
Ok(b) => {
tm_resp.push(Utc::now().naive_utc());
data.push(b);
},
Err(e) => eprintln!("Error:{}", e),
}
async {()}})
.await;
println!("{:#?}\n", &tm_quer);
println!("{:#?}\n", &tm_resp);
println!("{:#?}", &data);
}
Code returns:
[]
[
2026-02-14T18:54:53.546806100,
2026-02-14T18:54:53.549766100,
2026-02-14T18:54:53.550297900,
2026-02-14T18:54:53.551063300,
2026-02-14T18:54:53.551988600,
2026-02-14T18:54:53.552909100,
2026-02-14T18:54:53.556305,
2026-02-14T18:54:53.560614100,
2026-02-14T18:54:53.561075300,
2026-02-14T18:54:53.563943600,
]
[
b"data_from_site",
b"data_from_site",
b"data_from_site",
b"data_from_site",
b"data_from_site",
b"data_from_site",
b"data_from_site",
b"data_from_site",
b"data_from_site",
b"data_from_site",
]