Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for a result mapped future

Tags:

rust

future

I'm using the future library and I have a future which implements Future<T, E>. I'd like to map this future with a function FnOnce(T) -> D where D: From<E>. Now when I want to wait() for this future to finsih, I'll get a Result<Result<T, E>, D>, however I'd like a Result<T, D>.

Here's some example code for 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's the easiest and most understandable way of doing this (without matching)?

like image 280
torkleyy Avatar asked Feb 27 '17 15:02

torkleyy


1 Answers

This is for futures v0.1 (old, experimental)

I found an answer to the question:

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

parse(f.wait()?)

This should have equal semantics, because, when polled, the Future returned by map executes its closure. Another solution was to map a possible error and to use and_then:

f.map_error(|x| x.into()).and_then(|x| parse(x)).wait()
like image 89
torkleyy Avatar answered Nov 01 '22 07:11

torkleyy