Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

javascript - 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 */
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...