等待处理完成后再导出Node.js模块

Wait until processing completes before exporting Node.js module?

本文关键字:Node js 模块 处理 等待      更新时间:2023-09-26

我正在加载一个配置对象,然后在for中重新映射其属性。。在下面的循环中(它对.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
};

当我需要该模块时,显然还没有进行重新映射。我猜这是某种异步问题,但我不确定如何处理它。

您的代码是100%同步的,因此node执行所有"重新映射"代码在导出CCD_ 1对象之前同步。

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

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