A lightweight implementation of promises in Java
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
src/promiserpkg
.classpath
.gitignore
.project
LICENSE
README.md

README.md

Promiser-java

A lightweight implementation of Promises/A+ specification, inspiration taken from JavaScript.

Requirements

This library is written using Java 8 syntax.

Let's embrace the future ! 😄

To use this into Java 7, 6 and 5 projects, don't forget to install retrolambda by @orfjackal.

Usage

You can create a Promiser<T, U> object like this :

Promiser<T, U> p = new Promiser<T, U>((Resolver<T> resolve, Rejecter<U> reject) -> {

  // Place your asynchronous process here, and make sure
  // to trigger resolve.run() or reject.run() when needed.

});

<T> is the type of the result returned in case of success and <U> is the type of the result returned in case of error.

You can handle result and error cases like this now :

p.success((T result) -> {
  // Handle success here

})
.error((U err) -> {
  // Handle error here

})

Example

For example let's mock an asynchronous process using a Timer :

Promiser<String, Integer> p = new Promiser<String, Integer>((Resolver<String> resolve, Rejecter<Integer> reject) -> {
  int DELAY = 500;

  new Timer().schedule(new TimerTask() {
      @Override
      public void run() {
  	     resolve.run("I'm done !"); //resolving
         reject.run(404); //rejecting
      }
  }, DELAY);

});

Now we can handle the success or the error of this promise using the .success() and .error() callbacks :

p.success((String result) -> {
  // Handle success here
})
.error((Integer err) -> {
  // Handle failure here
})

Next step

  • Make a Promiser instance "thenable" so we can have a .then() and .catch() callbacks and provide an asynchronous flow control using .then() like this :
  p.then(...)
  .then(...)
  .then(...)
  .catch(...)