Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform array of promises into array of values when fulfilled

I'm after a function that would return a resolved value of a promise. Failing gracefully is definitely a bonus, but it's an assumed precondition that when the function is called the promise is ready to be resolved.

While I'm working with webdriver.js promise implementation which allows the queue manipulations similar to below, I don't want to get too lost in semantics of queues/chains etc. For that reason alone, here is some pseudocode to cover what I'm trying to achieve:

var inputs = [...], outputs;
outputs = inputs.map(function(input){
  //queue some async tasks to be performed with input
  queue.enqueue(...);
  //I can't return the *output* value here yet, naturally, so instead
  return promise;
});

//now I'll add another task to the same queue
//this means that by the time this task is run
//the async tasks above would have been executed
//and the promises would be "resolvable"... right?
queue.enqueue(function(){
  console.log(outputs); //>an array of promises
  console.log(doSomeMagic(outputs)); //>resolved values as needed <<<
});

NB: afaik Q.all() would not do what I'm after - it takes an array of promises and returns a promise of an array, not its resolved value. I'm only happy to be proved wrong.

like image 684
Oleg Avatar asked Aug 30 '13 06:08

Oleg


People also ask

How do you retrieve values from a Promise?

Use the Promise. then() method to access the value of a promise, e.g. p. then(value => console. log(value)) .

What is the fulfilled value of Promise all ()?

The fulfilled value is an empty array. If a nonempty iterable is passed, and all of the promises fulfill, or are not promises, then the promise returned by this method is fulfilled asynchronously.

Which is used to take an array of promises and returns a new Promise?

all() method is actually a method of Promise object (which is also an object under JavaScript used to handle all the asynchronous operations), that takes an array of promises(an iterable) as an input.


1 Answers

For anyone else looking for an answer based on the title of the question the following works with ES 2017+ to take an array of promises and return an array of values:

var arrayOfValues = await Promise.all(arrayOfPromises)
like image 132
Chris Magnuson Avatar answered Sep 29 '22 17:09

Chris Magnuson