1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
use futures::{Future, FutureExt};

/// For use with join! or try_join! Makes the future to run parallelly with other tasks instead of concurrently. See: <https://docs.rs/tokio/latest/tokio/macro.try_join.html#runtime-characteristics>.
pub async fn run_parallelly<T>(
    future: impl Future<Output = anyhow::Result<T>> + std::marker::Send + 'static,
) -> anyhow::Result<T>
where
    T: std::marker::Send + 'static,
{
    // boxing our futures helps avoid stack overflow
    let handle = tokio::spawn(future.boxed());
    match handle.await {
        Ok(Ok(result)) => Ok(result),
        Ok(Err(err)) => Err(err),
        Err(err) => anyhow::bail!("{}", err),
    }
}