Skip to content

Instantly share code, notes, and snippets.

@jedws
Created October 11, 2012 23:10
Show Gist options
  • Select an option

  • Save jedws/3876207 to your computer and use it in GitHub Desktop.

Select an option

Save jedws/3876207 to your computer and use it in GitHub Desktop.
Promise Map
/** the original Deferred (similar to jQuery) based implementation with lots of mutation */
public Promise<MyData> getMyDataAsync(String id) {
// create a new Deferred instance to represent this operation
final Deferred<MyData> deferred = Deferred.create();
// perform an async operation to get mydata, typically with a lower-level async api
rawDataClient.get(id)
// handle success case
.done(new Effect<Map<String, Object>>() {
public void handle(Map<String, Object> value) {
// convert the result into the target type and resolve the deferred
deferred.resolve(myDataFromRawData(value));
}
})
// use Promises.reject to forward failures to this higher-level deferred
.fail(reject(deferred));
// return the deferred's promise
return deferred.promise();
}
/** alternate version using Promise.map */
public Promise<MyData> getMyDataAsync(String id) {
// perform an async operation to get mydata, typically with a lower-level async api
return rawDataClient.get(id)
.map(new Function<Map<String, Object>, MyData>() {
public MyData apply(Map<String, Object> value) {
// convert the result into the target type
return myDataFromRawData(value);
}
};
}
/** composing multiple async ops with flatMap */
public Promise<MoreData> getMoreDataAsync(String id) {
// perform an async operation to get mydata, typically with a lower-level async api
return rawDataClient.get(id)
.flatMap(new Function<Map<String, Object>, Promise<MoreData>>() {
public Promise<MyData> apply(Map<String, Object> value) {
// make a further async call
return rawDataClient.getFromMyData(myDataFromRawData(value));
}
};
}
// the same as above (almost to the bytecode), but expressed in Scala:
def getMyDataAsync(id: String) =
// perform an async operation to get mydata, typically with a lower-level async api
rawDataClient.get(id).map { myDataFromRawData }
def getMoreDataAsync(id: String) =
rawDataClient.get(id).flatMap {
value => rawDataClient.getFromMyData(myDataFromRawData(value));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment