title: How do I return data from a callback inside an XMLHttpRequest using the JavaScript Exports Module pattern?
body: <p>I have this,</p>
  
  <pre><code>  var JOHNNY = (function()
      {
          var module = {};
          function getData(id, callback){
                  var xhr = new XMLHttpRequest();
                  var url = "http://someurl/api/5";
  
                  xhr.onreadystatechange = function () {
                      if (xhr.readyState == 4 &amp;&amp; (xhr.status == 200)) {
                          callback(xhr.response);
                      }
                  };
  
                  xhr.open("GET", url, true);
                  xhr.responseType = 'json';
                  xhr.send(null);
  
          }
          function myCallBack(data){
              return data;  //console.log works;
          }
          module.getStuff=function(id){
              return getData(5, myCallBack);  //just hardcoded id here
          }
          return module;
      })();
  </code></pre>
  
  <p>Data is returned.  I can step through it, but as soon as I run it in the console:</p>
  
  <pre><code>JOHNNY.getStuff(5);
  undefined
  </code></pre>
  
  <p>never get anything else (I'm in the console.)  If I change the return in the callback to <code>console.log(data)</code>, I get the data, so I know the url is good.</p>
  
  <p>Due to the async nature of the call, I put a callback.  But I am also trying to follow an "Exports" pattern variation of the Module pattern.</p>
  
  <p>How do I get the data from the callback?  I've seen lots of examples when not using the <a href="https://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript" rel="nofollow noreferrer">Exports</a> variation, but nothing else.   For example, this, <a href="https://stackoverflow.com/questions/24103503/javascript-module-pattern-with-ajax-callback">Javascript module pattern with Ajax callback</a>.  This one was never answered, <a href="https://stackoverflow.com/questions/37615084/returning-data-resolved-by-xmlhttprequest-with-module-pattern-function">Returning data resolved by XMLHttpRequest with module pattern function</a> and I evidently cannot understand this one, <a href="https://stackoverflow.com/questions/9490368/javascript-module-pattern-ajax-functions-callbacks">Javascript module pattern, ajax functions callbacks</a>.</p>
  
  <p>I can get the data if I do this,</p>
  
  <pre><code>function myCallBack(data){
      module.test = data;
  }
  </code></pre>
  
  <p>and then,</p>
  
  <pre><code>JOHNNY.test;
  </code></pre>
  
  <p>But I don't know if that's the right way or not.  Plus, how does this work when module has already been returned?</p>
  
  <p>I'm not using jQuery (please no jQuery response), just straight JavaScript.</p>
  
  <p>Edit:  I was hoping to fix this without Promises.  I do not understand why the callback does not fix the problem.</p>