title: In JavaScript, how to get back the results of a callback function for all the elements of an array, and execute some logic on them?
body: <p>I have a function that calls an API, and the API accepts a callback:</p>
  <pre><code>const callApi = async (param1, param2) =&gt; {
      api.doSomething(param1, param2, (result) =&gt; {
          // I want to return the result as the result of callApi
      }
  }
  </code></pre>
  <p>And I have a list/array of objects on which I want to call the Api function, treat the results one by one, and then sort them and pick the one that fits my criteria.</p>
  <p><strong>I do NOT want to shove all the logic in the callback.</strong>
  I know I could, but it would result in ugly looking code that will be hard to read 1 year from now.</p>
  <p>Something like:</p>
  <pre><code>let results = myArrayOfObjects.map(function(myObject){
      callApi(myObject.field1, myObject.field2)
          .then(
              // here I'd like to get the result of api.doSomething
              // do more stuff here with that result
          )
  
      // return an object here, or a promise
  
  })
  
  // do something with the results after all objects in myArrayOfObjects have been processed
  // for example, sort()
  </code></pre>
  <p>If the results are promises, I am thinking of using Promise.all to wait for all of them to complete.
  Otherwise, it would be even easier to work with the results.</p>
  <p>Thank you.</p>