Crate asynchronous [] [src]

A promise based asynchronous library

This library will provide an usefull way to invoke functions (clousures) in a Promise Style. A Promise is a Struct that represents the return value or the error that the funcion produces and it's executed in a separated thread.

Project github page

This project is based on the Q Promise library for Node JS .

Examples

This is a simple setup for a promise based execution:

use asynchronous::Promise;
 
Promise::new(|| {
  // Do something  
  let ret = 10.0 / 3.0;
  if ret > 0.0 { Ok(ret) } else { Err("Value Incorrect") }
}).then(|res| {            // res has type f64
  // Do something if the previous result is correct
  assert_eq!(res, 10.0 / 3.0);
  let res_int = res as u32 * 2;
  Ok(res_int)
}).finally_sync(|res| {    // res has type u32
  // Catch a correct result
  assert_eq!(res, 6u32);
}, |error| {
  // Catch an incorrect result
  unreachable!();
});

Using deferred execution of 1 simple tasks, 3 tasks in Parallel and 2 tasks in Series:

use asynchronous::Promise;
use asynchronous::Deferred;
use asynchronous::ControlFlow;

let d_a = Deferred::<&str, &str>::new(|| { Ok("a") });
let p_b = Promise::<&str, &str>::new(|| { Ok("b") });  // Executed right now
let d1 = Deferred::<u32, &str>::new(|| { Ok(1u32) });
let d2 = Deferred::<u32, &str>::new(|| { Err("Error Mock") });
let d3 = Deferred::<u32, &str>::new(|| { Ok(3u32) });
let d4 = Deferred::<u32, &str>::new(|| { Ok(4u32) });
let d5 = Deferred::<u32, &str>::new(|| { Ok(5u32) });

let promise = Deferred::vec_to_promise(vec![d1,d2,d3], ControlFlow::Parallel);
// Only d1, d2 and d3 are being executed at this time.

let value_b = d_a.to_promise().then(|res_a| {
    assert_eq!(res_a, "a");
    p_b.then(move |res_b| {
        Ok(res_a.to_string() + res_b)
    }).sync()
}).sync().unwrap();
assert_eq!(value_b, "ab");

promise.then(|res| {
    // Catch the result. In this case, tasks d4 and d5 never will be executed
    unreachable!();
    Ok(res)
}).fail(|error| {
    // Catch the error and execute another Promise
    assert_eq!(error, vec![Ok(1u32), Err("Error Mock"), Ok(3u32)]);    
    Deferred::vec_to_promise(vec![d4,d5], ControlFlow::Series).sync()
}).finally_sync(|res| {   // res : Vec<u32>
    // Do something here    
    assert_eq!(res, vec![4u32, 5u32]);
}, |error| { // error : Vec<Result<u32,&str>>
    // Do something here.
    unreachable!();
});

Structs

Deferred

Stores a function and delays its execution until it's transform to a promise. T : Type of value returned E : Type of error returned

Promise

Stores a result of previous execution tasks. T : Type of value returned E : Type of error returned

Enums

ControlFlow

Different possibilities for asynchronous treatment of vectors