title: Why doesn't my table creating function get populated with data inside a fetch call in JavaScript?
body: <p>This is my markup/HTML where the table will be inserted:</p>
  
  <pre><code>&lt;section class="page page-info"&gt;
    &lt;div class="contact"&gt;
      &lt;div class="container"&gt;
        &lt;div class="row"&gt;
          &lt;div class="col-sm-8 col-sm-offset-2"&gt;
              &lt;table&gt;
                  &lt;!-- Table goes here! --&gt;
              &lt;/table&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/section&gt;
  </code></pre>
  
  <p>Some variables in the outer scope so they can be accessed by all functions, followed by the fetch call and the table creating module :</p>
  
  <pre><code>var products;
  let table = document.querySelector('table');
  
  window
    .fetch('/pages/products-api')
    .then(resp =&gt; resp.json())
    .then(function(data) {
      products = data;
      GenerateTableModule.initialize(table, products);
  
      console.log('data.results ', data);
    })
    .catch(err =&gt; console.dir(err));
  
  const GenerateTableModule = (function() {
    let table = null;
    let data = [];
  
    function initialize(tableSelector, arr) {
      table = tableSelector;
      data = arr;
    }
  
    const _generateTableHead = function() {
      let thead = table.createTHead();
      let row = thead.insertRow();
      for (let key in data[0]) {
        let th = document.createElement('th');
        let text = document.createTextNode(key);
        th.appendChild(text);
        row.appendChild(th);
      }
    };
  
    const generateTable = function() {
      for (let element of data) {
        let row = table.insertRow();
        for (key in element) {
          let cell = row.insertCell();
          let text = document.createTextNode(element[key]);
          cell.appendChild(text);
        }
      }
      _generateTableHead();
    };
    return { initialize, generateTable };
  })();
  
  GenerateTableModule.generateTable();
  </code></pre>
  
  <p>The actual error I get in the console is:</p>
  
  <blockquote>
    <p>updating-upsell-on-the-view-cart.js?25617:26 Uncaught TypeError:
    Cannot read property 'createTHead' of null
        at _generateTableHead (updating-upsell-on-the-view-cart.js?25617:26)
        at Object.generateTable (updating-upsell-on-the-view-cart.js?25617:45)
        at updating-upsell-on-the-view-cart.js?25617:50</p>
  </blockquote>
  
  <p>But how can that be when I have my data being returned in the <code>console.log</code> in my fetch?!</p>
  
  <p><code>data.results  {products: Array(88)}</code></p>
  
  <p>Thanks in advance!</p>