title: Fetch Data Asynchronously Data Synchronously with JavaScript
body: <p>I want to fetch data and have it ready for another function to use as a javaScript object. The problem is that the data is fetched after the program completes. Here is the link to the project: <a href="https://github.com/bigbassroller/isomorphic-js/blob/master/src/components/pages/Home/HomeController.js" rel="nofollow">https://github.com/bigbassroller/isomorphic-js/blob/master/src/components/pages/Home/HomeController.js</a>. See code here:</p>
  
  <pre><code>import "babel-polyfill";
  import Controller from '../../../lib/controller';
  import nunjucks from 'nunjucks';
  import fetch from "isomorphic-fetch";
  import promise from "es6-promise";
  
  
  function onClick(e) {
    console.log(e.currentTarget);
  }
  
  function getData(context) {
   let data = {
    "name": "Leanne Graham"
   }
   return data;
  }
  
  function fetchData(context) {
      return fetch("http://jsonplaceholder.typicode.com/users/1").then(function(response) {
         let data = response.json().body;
         return data;
      });
  }
  
  
  export default class HomeController extends Controller {
  
  
    index(application, request, reply, callback) {
      this.context.cookie.set('random', '_' + (Math.floor(Math.random() * 1000) + 1), { path: '/' });
      this.context.data = { random: Math.floor(Math.random() * 1000) + 1 };
      callback(null);
    }
  
    toString(callback) {
  
      // Works 
      let context = getData(this.context);
      // Doesn't work
      // let context = fetchData(this.context);
  
      context.data = this.context.data;
  
      nunjucks.render('components/pages/Home/home.html', context, (err, html) =&gt; {
        if (err) {
          return callback(err, null);
        }
  
        callback(null, html);
      });
    }
  
    attach(el) {
      console.log(this.context.data.random);
      this.clickHandler = el.addEventListener('click', onClick, false);
    }
  
    detach(el) {
      el.removeEventListener('click', onClick, false);
    }
  
  }
  </code></pre>
  
  <p>Is it possible to have the data fetched before the  the page renders? I am trying to keep things as vanilla as possible, because I am trying to learn as much as possible. I've been stuck for days trying to solve this problem, so I am coming to SO for help, and to help others who have the same problem. 
  My issue is similar to this issue, <a href="https://github.com/reactjs/redux/issues/99" rel="nofollow">https://github.com/reactjs/redux/issues/99</a> but I am not trying to use redux, would rather use promises instead. </p>