Struct asynchronous::Deferred
[−]
[src]
pub struct Deferred<T, E> {
// some fields omitted
}Stores a function and delays its execution until it's transform to a promise. T : Type of value returned E : Type of error returned
Methods
impl<T, E> Deferred<T, E> where T: Send + 'static, E: Send + 'static[src]
fn new<F>(f: F) -> Deferred<T, E> where F: Send + 'static + FnOnce() -> Result<T, E>
Create a new task in deferred.
let deferred = asynchronous::Deferred::new(|| { // Do something if true { Ok("value a") } else { Err("Error description") } }); // At this point "deferred" is not executed
fn chain<TT, EE, F>(self, f: F) -> Deferred<TT, EE> where TT: Send + 'static, EE: Send + 'static, F: Send + 'static + FnOnce(Result<T, E>) -> Result<TT, EE>
Chain a deferred to another deferred.
let deferred = asynchronous::Deferred::new(|| { // Do something if true { Ok("value a") } else { Err("Error description") } }).chain(|res| { assert_eq!(res.unwrap(), "value a"); if true { Ok("value b") } else { Err("Error description") } });
fn to_promise(self) -> Promise<T, E>
Executes the task stored and returns a Promise
let deferred = asynchronous::Deferred::new(|| { // Do something if true { Ok("value a") } else { Err("Error description") } }); deferred.to_promise(); // At this point "deferred" is executing
fn vec_to_promise(vector: Vec<Deferred<T, E>>, control: ControlFlow) -> Promise<Vec<T>, Vec<Result<T, E>>>
Executes a vector of tasks and returns a Promise with a vector of values in case that all tasks ended ok. If there's one or more tasks with error, the promise fails and returns a vector with all the Results.
use asynchronous::{Deferred, ControlFlow}; let mut vec_deferred = Vec::new(); for i in 0..5 { vec_deferred.push(Deferred::<_,&str>::new(move || Ok(i) )) } let promise = Deferred::vec_to_promise(vec_deferred, ControlFlow::ParallelCPUS); // At this point all tasks in "vec_deferred" are executing assert_eq!(promise.sync().unwrap(), vec![0,1,2,3,4]);
fn first_to_promise(num_first: usize, wait: bool, vector: Vec<Deferred<T, E>>, control: ControlFlow) -> Promise<Vec<T>, Vec<Result<T, E>>>
Executes a vector of tasks and returns a Promise with a vector of the first num_first tasks that return Ok. If the wait parameter is true, the promise waits for all tasks that are running at that moment. If it's false, the promise returns once reaches the num_first tasks with Ok. If it's not possible achieve this number, the promise fails and returns a vector with all the Results.
use asynchronous::{Deferred, ControlFlow}; let mut v = vec![]; for i in 0..20 { v.push(Deferred::<u32, ()>::new(move ||{ Ok(i) })); } // The first 5 tasks that ended with Ok let _ = Deferred::first_to_promise(5, false, v, ControlFlow::ParallelLimit(3)) .finally_sync(|res| { assert_eq!(res.len(), 5); }, |_| { });