title: Wait for Inner Function to Complete Before Returning Value
body: <p>I have a function that makes a database query, then needs to return the result. </p>
  
  <p>The query is to a mysql database, using Node.js, the result is then returned to an Inquirer (NPM module) prompt.</p>
  
  <p>If this was a front end issue, I would use the built in promises of jquery: (example). $.ajax.done(). However the mysql NPM package doesn't have built in promises for the query() method.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>// OPTION 1, wait for query to complete before returning choicesArray (this example returns an empty array)
  
  choices() {
    let choicesArray = [];
    connection.query(`SELECT * FROM products`, (err, res)=&gt;{
      for (item of res) {
        choicesArray.push(`${item.product} | ${item.price}`);
      };
    });
    // wait here for query to complete
    return choicesArray;
  }
  
  
  
  // OPTION 2, change the syntax to take advantage of the query callback, something more like below (this example does not return the choicesArray all the way to the enclosing function)
  
  choices() {
    connection.query(`SELECT * FROM products`, (err, res)=&gt;{
      let choicesArray = [];
      for (item of res) {
        choicesArray.push(`${item.product} | ${item.price}`);
      };
      return choicesArray;
    });
  } // (node:3877) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: You must provide a `choices` parameter</code></pre>
  </div>
  </div>
  </p>