Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/yannickdot/promiser-java
A lightweight implementation of promises in Java
https://github.com/yannickdot/promiser-java
Last synced: about 6 hours ago
JSON representation
A lightweight implementation of promises in Java
- Host: GitHub
- URL: https://github.com/yannickdot/promiser-java
- Owner: YannickDot
- License: mit
- Created: 2015-10-12T09:43:59.000Z (about 9 years ago)
- Default Branch: master
- Last Pushed: 2015-10-15T08:45:09.000Z (about 9 years ago)
- Last Synced: 2024-04-18T12:56:16.430Z (7 months ago)
- Language: Java
- Size: 126 KB
- Stars: 9
- Watchers: 5
- Forks: 1
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Promiser-java
A lightweight implementation of [Promises/A+](https://promisesaplus.com) 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](https://github.com/orfjackal/retrolambda) by [@orfjackal](https://github.com/orfjackal).
### Usage
You can create a Promiser object like this :
``` java
Promiser p = new Promiser((Resolver resolve, Rejecter reject) -> {// Place your asynchronous process here, and make sure
// to trigger resolve.run() or reject.run() when needed.});
````` is the type of the result returned in case of success and `` is the type of the result returned in case of error.
You can handle result and error cases like this now :
```java
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 :
``` java
Promiser p = new Promiser((Resolver resolve, Rejecter 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 :
``` java
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 :
```java
p.then(...)
.then(...)
.then(...)
.catch(...)```