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

前端 未结 5 517
陌清茗
陌清茗 2020-12-09 16:30

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

var promises = [];
promises.push(myFunc         


        
5条回答
  •  一个人的身影
    2020-12-09 16:35

    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.

提交回复
热议问题