如果我有一些要链接在一起的期货,我怎样才能使第二个链接的未来以第一个未来的结果为条件?
对于一个人为的例子,我有类似的东西:
extern crate futures;
extern crate tokio_core;
use futures::{future, Future};
use tokio_core::reactor::Core;
fn add_one(x: i64) -> impl Future<Item = i64, Error = ()> {
future::ok(x).map(|x| x + 1)
}
fn double(x: i64) -> impl Future<Item = i64, Error = ()> {
future::ok(x).map(|x| x * 2)
}
fn add_one_then_double(x: i64) -> impl Future<Item = i64, Error = ()> {
future::ok(x).and_then(add_one).and_then(double)
}
fn main() {
let mut reactor = Core::new().unwrap();
println!("{:?}", reactor.run(add_one_then_double(10)).unwrap());
}
然后,我如何才能将未来更改为以add_one_then_double
未来的结果为条件add_one
,例如:
fn add_one_then_double_if_positive(x: i64) -> impl Future<Item = i64, Error = ()> {
future::ok(x).and_then(add_one).map(|v| {
if v >= 0 {
// chain the `double` future
} else {
// return `v` as the result
}
})
}