daily pastebin goal
52%
SHARE
TWEET

Untitled

a guest Mar 18th, 2019 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use futures;
  2. use futures::future::Either;
  3. use futures::sync::oneshot;
  4. use futures::Future;
  5. use std::thread;
  6. use std::time::Duration;
  7. use tokio;
  8.  
  9. #[derive(Debug)]
  10. struct MyError {
  11.     error_code: i32,
  12. }
  13.  
  14. impl From<oneshot::Canceled> for MyError {
  15.     fn from(_: oneshot::Canceled) -> MyError {
  16.         MyError { error_code: 1 }
  17.     }
  18. }
  19.  
  20. fn query_data() -> Result<i32, ()> {
  21.     Ok(1)
  22. }
  23.  
  24. fn send_promise_to_worker(sx: oneshot::Sender<i32>) -> Result<(), ()> {
  25.     // Send the oneshot somewhere in a way that might fail, eg. over a channel
  26.     thread::spawn(move || {
  27.         thread::sleep(Duration::from_millis(100));
  28.         sx.send(100).unwrap();
  29.     });
  30.     Ok(())
  31. }
  32.  
  33. fn deferred_task() -> impl Future<Item = i32, Error = MyError> {
  34.     let (sx, rx) = oneshot::channel();
  35.     match query_data() {
  36.         Ok(_i) => match send_promise_to_worker(sx) {
  37.             Ok(_) => Either::A(rx.map_err(|e| MyError::from(e))),
  38.             Err(_e) => Either::B(futures::failed(MyError { error_code: 2 })),
  39.         },
  40.         Err(_) => Either::B(futures::failed(MyError { error_code: 2 })),
  41.     }
  42. }
  43.  
  44. fn main() {
  45.     tokio::run(deferred_task().then(|r| {
  46.         println!("{:?}", r);
  47.         Ok(())
  48.     }));
  49. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top