Exporting Node module from promise result
<p>I'm trying to rewrite a module to return a different value than before, but now it uses an async call to get that value. (with <code>child_process</code> if it matters). I've wrapped it in a Promise, but that's not critical to me - it can be in the original child_process callback, but the problem is I can't chain the promise to everywhere in the app because I need this to become synchronous. Here's my module:</p>
<pre class="lang-js prettyprint-override"><code>const { exec } = require(&quot;child_process&quot;);

const platformHome = process.env[process.platform === &quot;win32&quot; ? &quot;USERPROFILE&quot; : &quot;HOME&quot;];

const getExecPath = new Promise((resolve, reject) =&gt; {
  const path = process.env.GEM_HOME;

  if (path) {
    resolve(path);
    return;
  }
  exec(&quot;gem environment&quot;, (err, stdout, err) =&gt; {
    if (err) {
      reject(err);
    }
    const line = stdout.split(/\r?\n/).find(l =&gt; ~l.indexOf(&quot;EXECUTABLE DIRECTORY&quot;));
    if (line) {
      resolve(line.substring(line.indexOf(&quot;: &quot;) + 2));
    } else {
      reject(undefined);
    }
  });
});

let GEM_HOME = undefined;

getExecPath
  .then(path =&gt; (GEM_HOME = path))
  .catch(() =&gt; (GEM_HOME = `${platformHome}/.gem/ruby/2.3.0`))
  .then(
    () =&gt; (module.exports = GEM_HOME) // or simply return it
  );
</code></pre>
<p>Clearly, when requiring the module, this doesn't work - and if I return the promise itself, and use <code>then</code> after <code>require</code> - my next <code>module.exports</code> will be async, and this chain will carry on. How do I avoid this pattern?</p>