jdeferred / jdeferred

Java Deferred/Promise library similar to JQuery.

Home Page:jdeferred.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Promise.then() is difficult to use with lambdas

aalmiray opened this issue · comments

Currently Promise.then takes 3 different types of inputs: DoneCallback, DoneFilter, and DonePipe. This forces explicit casts when using lambda expressions. It would be better if this method were to be split in 3 variants, such as

then(DoneCallback cbk)
thenFilter(DoneFilter fltr)
thenPipe(DonePipe pipe)

filter() is actually misleading term here as the operation executed here is mostly referred to as map().
So maybe all the filter need to be renamed to follow common naming and help to reduce the learning curve.

That's a good point @sclassen. This is the right time to provide an alias and deprecate filter or do a full rename given that we're braking binary compatibility.

My proposal for renaming (based on the naming in java streams and vavr.io):
filer -> map
pipe -> flatMap

The code would then read as follows:

someCallToDbReturningAPromise(id)
    .map(t -> t.name())
    .flatMap(name -> callSomeBackgroundTaskReturningAPromise(name))
    .then(result -> saveToMap(result));

I get s/filter/map/ but isn't pipe a variation of mapas well?

yes.
DoneFilter returns D_OUT which is then wrapped in a new Promise<D_OUT, F, P>, where as DonePipe returns Promise<D_OUT, F_OUT, P_OUT>
So if we would apply the DonePipe as a map() we would get Promise<Promise<D_OUT, F_OUT, P_OUT>, F, P>
Because this is just complicated and does not add any value the pipe operation unwraps the inner promise.
The same does the flatMap() on streams. it unwraps a stream in a stream -> it flattens the generic...

Does this explanation help?