Java Promise is a promise implement by Java1.7 like javascript.
The Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet, but is expected in the future.
new Promise(new Resolver() {
public void execute(OnFulfill<Object, Object> onFulfill, OnReject<Object, Object> onReject) throws Exception {
...
}
} )Parameters
- Resolver is the same as:
function(resolve, reject){...}
A Promise is in one of these states:
- pending:initial state, not fulfilled or rejected.
- fulfilled:meaning that the operation completed successfully.
- rejected:meaning that the operation failed.
- Promise.all(Promise... promises)
Promise.all(Promise.resolve(1), Promise.resolve(2)) - Promise.race(Promise... promises)
Promise.race(Promise.resolve(1), Promise.reject(2)) - Promise.resolve(value)
Promise.resolve("resovle") - Promise.reject(value)
Promise.reject("reject")
- promise.then(OnFulfill onFulfill, OnReject onReject)
- promise.then(OnFulfill onFulfill)
- promise.Catch(OnReject onReject)
Example1
//if the random index is equal to 0 , print "success result : 1",
the random index is equal to 1, print "error result : 0"
new Promise(new Resolver() {
public void execute(OnFulfill<Object, Object> onFulfill, OnReject<Object, Object> onReject) throws Exception {
int index = new Random().nextInt(2);
if (index == 0) onFulfill.execute(index);
else onReject.execute(index);
}
}).then(new OnFulfill<String, Integer>() {
public String execute(Integer i) {
return "success result : " + i;
}
}, new OnReject() {
public Object execute(Object args) {
return "error result : " + args;
}
})Example2
//print "last result : 1"
Promise.resolve("1").then(new OnFulfill() {
public Object execute(Object args) {
System.out.println("last result : " + args);
return null;
}
});
//print "This is my exception, last result is 1"
Promise.resolve("1").then(new OnFulfill() {
public Object execute(Object args) throws Exception{
throw new Exception("This is my exception, last result is "+args);
}
}).Catch(new OnReject<Object, Exception>() {
public Object execute(Exception e) throws Exception {
System.out.println(e.getMessage());
return null;
}
});About Promise :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
