In Javascript, I can wrap a callback as a promise as folllows:
function subscribeAsCallback(request, callback) {
// ... async operation
const response = ...;
callback(response);
}
function subscribeAsPromise(request) {
return new Promise((resolve, reject) => {
subscribeAsCallback(request, (response) => {
resolve(response);
});
});
}
So that I can call it with
subscribeAsPromise(request).then(response => {
// handling response logic
});
And I would like to ask what is the equivalent of it in Java? Here is my code in Java, where I have no idea how to wrap the callback up.
public class DataSubscriber {
public void subscribeAsCallback(Request request, Consumer<Response> consumer) {
// ... async operation
Response response = ...;
consumer.accept(response);
}
public CompletableFuture<Response> subscribeAsPromise(Request request) {
// ... ?
// what is the equivalent of its Java version?
}
}
So that I can call the code as follows:
dataSubscriber.subscribeAsPromise(request).thenApply(response -> {
// handling response logic
});