title: How do I return the response from an asynchronous call?
body: <p>How do I return the response/result from a function <code>foo</code> that makes an asynchronous request?</p>
  <p>I am trying to return the value from the callback, as well as assigning the result to a local variable inside the function and returning that one, but none of those ways actually return the response — they all return <code>undefined</code> or whatever the initial value of the variable <code>result</code> is.</p>
  <p><strong>Example of an asynchronous function that accepts a callback</strong> (using jQuery's <code>ajax</code> function):</p>
  <pre><code>function foo() {
      var result;
  
      $.ajax({
          url: '...',
          success: function(response) {
              result = response;
              // return response; // &lt;- I tried that one as well
          }
      });
  
      return result; // It always returns `undefined`
  }
  </code></pre>
  <p><strong>Example using Node.js:</strong></p>
  <pre><code>function foo() {
      var result;
  
      fs.readFile(&quot;path/to/file&quot;, function(err, data) {
          result = data;
          // return data; // &lt;- I tried that one as well
      });
  
      return result; // It always returns `undefined`
  }
  </code></pre>
  <p><strong>Example using the <code>then</code> block of a promise:</strong></p>
  <pre><code>function foo() {
      var result;
  
      fetch(url).then(function(response) {
          result = response;
          // return response; // &lt;- I tried that one as well
      });
  
      return result; // It always returns `undefined`
  }
  </code></pre>