Search code examples
javascriptcallbackes6-promise

JS Promise Callbacks: Get named params instead of array


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

  }

Solution

  • 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