0

Is there a way to return early from a future combinator chain? For example, I'd like to return success if some condition holds, otherwise keep going down the chain.

I want to do something similar to this:

fn early_exit() -> impl Future<Item = u32, Error = String> {
    ok::<u32, String>(42)
        .and_then(some_function)
        .and_then(another_function)
        .and_then(|x| {
            // return early if condition is satisfied
            if some_condition(x) {
                return ok::<u32, String>(42);
            }
            // Else pass it down the combinator chain for further transformations
            else {
                Ok(x)
            }
        })
        .and_then(one_more_function)
        .and_then(last_function)
}

I think this should be doable with async/await, but is there a good way to do this with futures 0.1?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
pd176
  • 821
  • 3
  • 10
  • 20
  • your example don't make sense just call your conditional future inside the `and_then()` `str_to_u32(x)` in place of `Ok(x)` – Stargateur Dec 13 '19 at 14:16
  • @Stargateur Maybe I didn't explain the problem well enough. I updated the example. Hopefully it makes sense now – pd176 Dec 13 '19 at 14:25
  • It looks like your question might be answered by the answers/linked questions of [How to return early from a Rust function that returns a future?](https://stackoverflow.com/q/53551385/155423); [Is there any way to return from a function from inside a closure?](https://stackoverflow.com/q/52027634/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Dec 13 '19 at 14:40
  • It's hard to answer your question because it doesn't include a [MRE]. We can't tell what crates (and their versions), functions, variables, etc. are present in the code. It would make it easier for us to help you if you try to reproduce your error on the [Rust Playground](https://play.rust-lang.org) if possible, otherwise in a brand new Cargo project, then [edit] your question to include the additional info. There are [Rust-specific MRE tips](//stackoverflow.com/tags/rust/info) you can use to reduce your original code for posting here. Thanks! – Shepmaster Dec 13 '19 at 14:42
  • The real answer is "use async/await" – Boiethios Dec 13 '19 at 14:43
  • 1
    Does this answer your question? [How do I conditionally return different types of futures?](https://stackoverflow.com/questions/51885745/how-do-i-conditionally-return-different-types-of-futures) – Stargateur Dec 13 '19 at 16:29
  • I forget about use either but I still still maintain my comment :p – Stargateur Dec 13 '19 at 16:29

0 Answers0