0

I'm taking a JavaScript course and I'm creating my own "challenge". Unfortunately, it takes the teachers days to respond, and I don't have that long. I tried searching for the answer, but I seem to have come up short.

I created a database and pumped the select * results out to a page to simulate an ajax call. I then wrote the following code:

const dataModule = (function() {

  //fetch all data from ajax
  return {
    getData: function() {
      const famData = fetch('http://localhost/Test2/ajaxservers/_test.php')
        .then(result => {
          return result.json()
        });
    }
  }

})();

const uiModule = (function() {

  //some code

})();

const controlModule = (function(data, ui) {

  console.log(data.getData());

})(dataModule, uiModule)

as you can see, I'm using the Module pattern. I return a function in the dataModule to fetch the data. the function seems to work OK. if I add a line to it to do .then(data=> console.log(data)); I see the array returned, but if I call the function from the controlModule without console logging the fetch data, I get undefined. What am I missing?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • (1) Your `getData` function does not have a `return` (2) If you would return `famData`, you would return a promise. This is the best you can do, as it is impossible to return *now* what only becomes available in the *future*. Don't expect to get the data in a synchronous way. Embrace asynchrony. – trincot May 06 '20 at 18:05
  • that's a good point. I'm not thinking asynchronously. I totally see now why the function call in the controlModule comes back undefined. Now to figure out how to reorganize this. – Justin Egan May 06 '20 at 18:43
  • (1) `return famData`; (2) prefix `function(data, ui)` with `async`; (3) prefix `data.getData()` with `await`. – trincot May 06 '20 at 19:05
  • I see. I end up returning a promise that I can then consume. Would it be a good idea to not use the module setup? seems to just cause hassles. – Justin Egan May 06 '20 at 19:11
  • You can just do `result = await (await fetch(url)).json()` within an async function. – trincot May 06 '20 at 19:26

0 Answers0