Search code examples
javascriptes6-promise

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 */
});

Solution

  • 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"];
    }