Hi Alain,

Unsurprisingly this isn’t very hard to do:

    private PromiseFactory pf;
    
    public <T> Promise<T> toPromise(CompletionStage<T> cs) {
        Deferred<T> deferred = pf.deferred();
        cs.whenComplete((r,e) -> {
            if(e == null) {    
                deferred.resolve(r);    
            } else {    
                deferred.fail(e);    
            }    
        });
        return deferred.getPromise();
    }
    
    public <T> Promise<T> toPromise(CompletableFuture<T> cf) {
        if(cf.isDone() && !cf.isCompletedExceptionally()) {
            return pf.resolved(cf.getNow(null));
        } else {
            return toPromise((CompletionStage<T>) cf);    
        }
    }

Note that the CompletableFuture version is just a way to optimise when the 
Completable Future is already successfully resolved (the API for consuming 
failures is so bad that it’s not worth trying to optimise the already failed 
case).

Best Regards,

Tim

> On 28 Oct 2018, at 15:41, Alain Picard via osgi-dev <osgi-dev@mail.osgi.org> 
> wrote:
> 
> We are now using Promises all over the place, but we are finding ourselves 
> using a library that uses CompletableFuture and want our service based on 
> that library to convert those futures into promises.
> 
> Has anyone done this before? While I can surely find a way of doing it, I 
> would like to get some best practice advice from the experts.
> 
> Cheers,
> Alain
> 
> _______________________________________________
> OSGi Developer Mail List
> osgi-dev@mail.osgi.org
> https://mail.osgi.org/mailman/listinfo/osgi-dev

_______________________________________________
OSGi Developer Mail List
osgi-dev@mail.osgi.org
https://mail.osgi.org/mailman/listinfo/osgi-dev

Reply via email to