Waiting for a future outcome

I use the future , and I have a future that realizes Future<T, E>. I would like to draw this future using the FnOnce(T) -> Dwhere function D: From<E>. Now that I want wait()finsih for this future, I will receive Result<Result<T, E>, D>, however I would like to Result<T, D>.

Here is a sample code for a better understanding:

struct ReadError;

enum DownloadError {
    Read(ReadError),
    Parse(ParseError),
}

impl From<ReadError> for DownloadError { ... }

fn parse(bytes: [u8; 4]) -> Result<i32, DownloadError> { ... }

fn map_and_wait<F: Future<Item = [u8; 4]; Error = ReadError>>(f: F) -> Result<i32, DownloadError> {
    match f.map(|x| parse(x)).wait() {
        Ok(Ok(x)) => Ok(x),
        Ok(Err(x)) => Err(x.into()),
        Err(x) => Err(x),
    }
}

What is the easiest and most understandable way to do this (without matching)?

+4
source share
1 answer

I found the answer to the question:

You can just waitfinish in the future first , use ?to return a potential error, and then apply to it parse:

parse(f.wait()?)

, Future, map. and_then:

f.map_error(|x| x.into()).and_then(|x| parse(x)).wait()
+2

Source: https://habr.com/ru/post/1670946/


All Articles