Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best es6 way to get name based results with Promise.all

By default the Promise.All([]) function returns a number based index array that contains the results of each promise.

var promises = []; promises.push(myFuncAsync1()); //returns 1 promises.push(myFuncAsync1()); //returns 2 Promise.all(promises).then((results)=>{     //results = [0,1] } 

What is the best vanilla way to return a named index of results with Promise.all()?

I tried with a Map, but it returns results in an array this way: [key1, value1, key2, value2]

UPDATE:

My questions seems unclear, here is why i don't like ordered based index:

  1. it's crappy to maintain: if you add a promise in your code you may have to rewrite the whole results function because the index may have change.
  2. it's awful to read: results[42] (can be fixed with jib's answer below)
  3. Not really usable in a dynamic context:
var promises = []; if(...)     promises.push(...); else{     [...].forEach(... => {          if(...)             promises.push(...);         else             [...].forEach(... => {                 promises.push(...);             });     }); } Promise.all(promises).then((resultsArr)=>{     /*Here i am basically fucked without clear named results          that dont rely on promises' ordering in the array */ }); 
like image 971
Anthony Bobenrieth Avatar asked Feb 09 '16 16:02

Anthony Bobenrieth


2 Answers

ES6 supports destructuring, so if you just want to name the results you can write:

var myFuncAsync1 = () => Promise.resolve(1);  var myFuncAsync2 = () => Promise.resolve(2);    Promise.all([myFuncAsync1(), myFuncAsync2()])    .then(([result1, result2]) => console.log(result1 +" and "+ result2)) //1 and 2    .catch(e => console.error(e));

Works in Firefox and Chrome now.

like image 176
jib Avatar answered Sep 24 '22 10:09

jib


Is this the kind of thing?

var promises = []; promises.push(myFuncAsync1().then(r => ({name : "func1", result : r}))); promises.push(myFuncAsync1().then(r => ({name : "func2", result : r}))); Promise.all(promises).then(results => {     var lookup = results.reduce((prev, curr) => {         prev[curr.name] = curr.result;         return prev;     }, {});     var firstResult = lookup["func1"];     var secondResult = lookup["func2"]; } 
like image 34
spender Avatar answered Sep 25 '22 10:09

spender