0

I have two asynchronous calls, I want to (kind of) merge the response from call 1 with the response from call 2 in an object.

The code below does this/works. My question: Is there a way to make the callback params from Promise.all a bit more readable? I don't really like to use an array in this case.

function getOptions() {

      let programRequest = someAsynFunc(...);
      let overviewTypeRequest = someOtherAsynFunc(...);

      return Promise.all([programRequest, overviewTypeRequest]).then(values => {
          return {
              programs: values[0],
              overviewTypes: values[1]
          }
      });

  }
sandrooco
  • 8,016
  • 9
  • 48
  • 86
  • Possible duplicate of [Best es6 way to get name based results with Promise.all](http://stackoverflow.com/questions/35297446/best-es6-way-to-get-name-based-results-with-promise-all) – jib Mar 27 '17 at 15:56

2 Answers2

2

Take a look at array destructuring. You can do this:

return Promise.all([programRequest, overviewTypeRequest])
  .then(([programs, overviewTypes]) => {
    return {
      programs,
      overviewTypes,
    }
  });

Since the variables are the same name as your object properties you can also take advantage of object shorthand notation.

For reference:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer

Christopher
  • 856
  • 9
  • 16
1

Yes: With ES6 destructuring:

Promise.all([...]).then(([programs, overviewTypes] => ({programs, overviewTypes}));
//                       ^ destructuring               ^ short object literal syntax
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308