Brett Brett - 6 months ago 299
Node.js Question

Asynchronous nodejs module exports

I was wondering what the best approach is for configuring a module export. "async.function" in the example below could be a FS or HTTP request, simplified for the sake of the example:

Here's example code (asynmodule.js):

var foo = "bar"
async.function(function(response) {
foo = "foobar";
// module.exports = foo; // having the export here breaks the app: foo is always undefined.
});

// having the export here results in working code, but without the variable being set.
module.exports = foo;


How can I export the module only once the async callback has been executed?

edit
a quick note on my actual use-case: I'm writing a module to configure nconf (https://github.com/flatiron/nconf) in an fs.exists() callback (i.e. it will parse a config file and set up nconf).

Answer

Your export can't work because it is outside the function while the foodeclaration is inside. But if you put the export inside, when you use your module you can't be sure the export was defined.

The best way to work with an ansync system is to use callback. You need to export a callback assignation method to get the callback, and call it on the async execution.

Example:

var foo, callback;
async.function(function(response) {
    foo = "bar"
    if (exists){
        foo = "foobar";
    }

    if( typeof callback == 'function' ){
        callback(foo);
    }
});

module.exports = function(cb){
    if(typeof foo != 'undefined'){
        cb(foo); // If foo is already define, I don't wait.
    } else {
        callback = cb;
    }
}

In main

var fooMod = require('./foo.js');
fooMod(function(foo){
    //Here code using foo;
});