advantageous / qbit

The Java microservice lib. QBit is a reactive programming lib for building microservices - JSON, HTTP, WebSocket, and REST. QBit uses reactive programming to build elastic REST, and WebSockets based cloud friendly, web services. SOA evolved for mobile and cloud. ServiceDiscovery, Health, reactive StatService, events, Java idiomatic reactive programming for Microservices.
http://advantageous.github.io/qbit/
Apache License 2.0
709 stars 140 forks source link

Chaining Promises of different types #728

Closed SagarN closed 8 years ago

SagarN commented 8 years ago

698 Solves the issue of chaining Promises of same type.

I would like to chain Promise of Type K , then Promise of Type L

promiseK.thenPromise(promiseL).thenPromise(promiseM).....

RichardHightower commented 8 years ago

Sagar,

I think this exists already. It is called thenMap.

https://github.com/advantageous/reakt/wiki/Promise.thenMap

The method Promise.thenMap converts one type of promise into another.

Let's say for example you are storing data into Cassandra. You want to convert a promise that returns a Cassandra ResultSet into a promise that returns a Boolean.

Example using converting a promise for Cassandra ResultSet into a boolean promise.


        final Promise<ResultSet> resultSetPromise = Promises.<ResultSet>promise();
        final Promise<Boolean> promise = resultSetPromise
                .thenMap(ResultSet::wasApplied) // <-------------- see thenMap
                .catchError((error) -> {
                        if (error instanceof DriverException) {
                            logger.error("Error " + message, error);
                            errorCount.incrementAndGet();
                        }
                });
        /* registerCallback is from Reakt Guava Bridge 
           It converts ListableFutures into Reakt promises (to/fro).
        */
        registerCallback(resultSetFuture, resultSetPromise); 

Here is a simpler example that turns an Employee Promise into a Sheep Promise.

Converting an employee into a sheep.

        Promise<Employee> employeePromise = Promises.<Employee>promise();

        Promise<Sheep> sheepPromise = employeePromise
                .thenMap(employee1 -> new Sheep(employee1.id));

        employeeService.lookupEmployee("id123", employeePromise);

If that is not what you want, please let me know. Just reopen this issue with a comment.