我正在加载一个配置对象,然后在下面的 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/