Thursday, June 20, 2019

javascript - Exporting Node module from promise result

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 child_process 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:



exec = require('child_process').exec

platformHome = process.env[if process.platform is 'win32' then 'USERPROFILE' else 'HOME']


getExecPath = new Promise (resolve, reject) ->
path = process.env.GEM_HOME

if path
resolve(path)
else
exec 'gem environment', (err, stdout, stderr) ->
unless err
line = stdout.split(/\r?\n/)

.find((l) -> ~l.indexOf('EXECUTABLE DIRECTORY'))
if line
resolve line[line.indexOf(': ') + 2..]
else
reject undefined

GEM_HOME = undefined

getExecPath.then (path) ->
GEM_HOME = path

.catch ->
GEM_HOME = "#{platformHome}/.gem/ruby/2.3.0"
.then =>
module.exports = GEM_HOME // or simply return it


Clearly, when requiring the module, this doesn't work - and if I return the promise itself, and use then after require - my next module.exports will be async, and this chain will carry on. How do I avoid this pattern?

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...