title: JavaScript ES6 Module OnLoad handler implementation
body: <p>I have a NodeJS server application which is split to lost of ES6 modules. I am trying to create a kind of "load module handler", a function in the main module, which other modules would require to register a callback, which will be executed after the main module is fully initialized. I am using Babel (with <code>babel-preset-es2015</code>) to transpile ES6 modules into executable JavaScript.</p>
  
  <p>To demonstrate the issue here in short, I've created 2 sample files.</p>
  
  <p>File <code>index.js</code> (application entry, main module):</p>
  
  <pre><code>import * as js2 from "./js2.js";
  
  let toCall = [], // this array handles callbacks from other modules
      initialized = false; // flag
  
  export function onInit (cb) { // registers cb to execute after this module is initialized
      if (initialized) {
          cb();
          return;
      }
      toCall.push(cb);
  }
  
  function done () { // initialization is done - execute all registered callbacks
      toCall.forEach(f =&gt; f());
  }
  
  // some important stuff here
  // callback(() =&gt; {
          initialized = true;
          done();
  // });
  </code></pre>
  
  <p>And the other module <code>js2.js</code>:</p>
  
  <pre><code>import { onInit } from "./index";
  
  onInit(() =&gt; {
      console.log("Now I can use initialized application!");
  });
  </code></pre>
  
  <p>All seems to be OK to me, but unfortunately this doesn't work throwing the next error in the first file:</p>
  
  <pre><code>Cannot read property 'push' of undefined
  </code></pre>
  
  <p>Thing is, there is no <code>toCall</code> variable at this point, but why? Variable <code>toCall</code> is declared <em>before</em> <code>onInit</code> function, it must be ready to use in <code>onInit</code>, mustn't it? How to solve this and is my way rational enough to implement something called "module initialization callbacks"? Are there any other solutions for this?</p>
  
  <p>Thank you for any help and advice.</p>