By using join_all we can execute a batch of futures simultaneously and get the results at once, but sometime we need to map the original parameter with its result, how can we achieve that? Like the code below, I want to know which result associates with the tx_id passed into the future, can we make this?

let fs = items
    .iter()
    .map(|item| {
        let tx_id = item.block_transaction_id.clone();
        let c = self
            .block_client
            .get_transaction_height(tx_id.clone())
            .map(|c| (tx_id, c)); // How can I pass tx_id associated to the future to the end?
        c
    })
    .collect_vec();

let results = futures::future::join_all(fs).await;
for result in results {
    match result {
        Ok((tx_id, h)) => {},
        Err(e) => {}
    }
}
1

There are 1 best solutions below

1
On

Pretty much like that? futures::FutureExt adds a map method to futures themselves so you can map a Future<Output=A> to a Future<Output=B>.

You don't provide any information as to what get_transaction_height does or what its types are (and this is why you're supposed to provide a minimal reproducible example), but here it looks like get_transaction_height() -> impl Future<Output=Result<...>>, this means your map is mapping to Output=(Id, Result<...>), therefore your match should be something along the lines of:

    match result {
        (id, Ok(h)) => {},
        (id, Err(e)) => {}
    }

but since you ­­-- again -- don't provide much in the way of actionable information, there's not much else which can be help with.