use std::future::Future;
use std::pin::Pin;
use async_trait::async_trait;
use anyhow::Result;
#[async_trait]
pub trait AndThenAsync<T, U, F>
where
F: FnOnce(T) -> Pin<Box<dyn Future<Output = U> + Send>> + Send {
type Output;
async fn and_then_async(self, map: F) -> Self::Output;
}
#[async_trait]
impl<'a, T, U, F> AndThenAsync<T, U, F> for Option<T>
where
T: Send,
U: Send,
F: 'static + FnOnce(T) -> Pin<Box<dyn Future<Output = U> + Send>> + Send,
{
type Output = Option<U>;
async fn and_then_async(self, map: F) -> Self::Output {
match self {
Some(t) => {
let u = map(t).await;
Some(u)
}
None => None,
}
}
}
#[async_trait]
impl<'a, T, U, F> AndThenAsync<T, U, F> for Result<T>
where
T: Send,
U: Send,
F: 'static + FnOnce(T) -> Pin<Box<dyn Future<Output = U> + Send>> + Send,
{
type Output = Result<U>;
async fn and_then_async(self, map: F) -> Self::Output {
match self {
Ok(t) => {
let u = map(t).await;
Ok(u)
}
Err(e) => Err(e),
}
}
}