javascript - 等到处理完成后再导出 Node.js 模块?

标签 javascript arrays node.js asynchronous commonjs

我正在加载一个配置对象,然后在下面的 for..in 循环中重新映射其属性(它对 .styles 的值进行一些字符串连接,而 .styles 只是一个字符串数组)。当我需要该模块时,显然没有发生重新映射。我猜这是某种异步问题,但我不确定如何处理它。有什么建议吗?

// 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.

您的代码是 100% 同步的,因此 Node 会执行所有“重新映射”代码 在导出 bundle 对象之前同步。

我认为,你的问题是Array.prototype.map()不修改数组,而是返回新数组。因此,您应该自己为 bundle[key].styles 分配新值:

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

关于javascript - 等到处理完成后再导出 Node.js 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30551026/

相关文章:

javascript - 笑脸解析器和 xss 注入(inject)保护

javascript - 检测 odoo 界面何时完全加载

javascript - js 是否有可能尊重这个条件?

Javascript 根据长度和键值修改数组

javascript - 从对象数组中删除相同的值

node.js - 如何在 Typescript 中声明 NodeJs 模块?

javascript - Angular2 : AsyncPipe and Observable, 无法检索属性(TypeError : Cannot read property . .. of null)

javascript - 数组自引用映射 - 非常奇怪的结果

javascript - 是否可以在 sequelize 中基于关联进行查询?

node.js - 将 csv 文件上传到 Web api 时出现 502 错误