Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Like "Promise.all" on Java 8 (maybe with lambdas)

I would like to know if there is something similar to the "Promise.all" of JavaScript for Java 8 (currently on Android). I am trying to make when all the callbacks finish, then execute a second process.

Now the callbacks that I am using are lambdas expressions, but I'm open to suggestions to change the way to do the callbacks and the "big callback" that is executed when all callbacks finishes.

I made it with a counter of callbacks, that when that counter of callbacks is equal to the length of callbacks then call to the big callback. But I am sure that this solution is not the correct one.

like image 514
Alberto Avatar asked Jan 29 '19 16:01

Alberto


People also ask

What are the 3 states of a JavaScript Promise?

A Promise is in one of these states: pending: initial state, neither fulfilled nor rejected. fulfilled: meaning that the operation was completed successfully. rejected: meaning that the operation failed.

What is Promise all in JavaScript?

all() The Promise. all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will fulfill when all of the input's promises have fulfilled, or if the input iterable contains no promises.

What is the alternative of Promise in JS?

Javascript. 2. Async/Await: Async/Await is used to work with promises in asynchronous functions.

Is Promise all concurrent?

JavaScript's Promise. all() method takes in a parameter of iterable promises runs them concurrently then returns a single Promise that resolves to an array of results of the input promises.


1 Answers

Java 8 offers this as CompletableFuture.allOf(CompletableFuture...), which mimics Promise.all; there is also CompletableFuture.anyOf(CompletableFuture...) to mimic Promise.race in Javascript.

If you use ListenableFuture instead, Guava does this as Futures.allAsList(...), with both varargs and iterable overloads.

like image 118
Jeff Bowman Avatar answered Oct 18 '22 01:10

Jeff Bowman