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:
results[42]
(can be fixed with jib's answer below)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 */ });
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.
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"]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With