简体   繁体   中英

Wait until processing completes before exporting Node.js module?

I'm loading a configuration object, then remapping its properties in the for..in loop below (it does some string concatenation on the values of .styles which is just an array of strings). When I'm requiring the module, the re-mapping clearly hasn't occurred. I'm guessing this is some sort of async issue, but I'm not sure how to handle it. Any suggestions?

// Init vars
var buildConfig = require('./build-config.js');
var cssPath = buildConfig.paths.cssPath;
var bundle = buildConfig.bundle;

// Callbacks
var setPathsGeneric = function(basePath, extName) { // Currying function
    return function(val, index, self) {
        return basePath + val + extName;
    };
};
var setCSSPaths = setPathsGeneric(cssPath, '.css');

// Map key values to actual URL paths
for (var key in bundle) {
    if(bundle[key].styles && bundle[key].styles.length) {
        bundle[key].styles.map(setCSSPaths);
    } 
}

module.exports = {
    bundle: bundle
};

When I'm requiring the module, the re-mapping clearly hasn't occurred. I'm guessing this is some sort of async issue, but I'm not sure how to handle it.

Your code is 100% synchronous, so node executes all your "re-mapping" code synchronously before exporting bundle object.

I think, your problem is that Array.prototype.map() do not modify an array, but returns new array instead. So, you should assign new value to bundle[key].styles yourself:

bundle[key].styles = bundle[key].styles.map(setCSSPaths);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM