【问题标题】:Only return module.exports once npm.load callback is returned仅在返回 npm.load 回调后才返回 module.exports
【发布时间】:2016-12-10 11:11:35
【问题描述】:

这是我目前正在经历的一个简化示例。

index.js

var config = require('../config.js');
console.log(config.globalModules); //undefined

config.js 使用外部包 (npm) 来帮助填充其 module.exports 对象。

config.js

var npm = require('npm');
var glob = require('glob');

module.exports = {}

// The majority of methods rely on properties which are not set until npm.load has been called.

npm.load(function (er) {
    // now i can use npm properties and methods
    module.exports.globalModules = glob.sync('*', { cwd: npm.globalDir})
    module.exports.localModules  = glob.sync('*', { cwd: npm.dir})
});

我已阅读此处的所有异步/同步回调问题,并尝试使用同步包解决此问题,但失败了。我尝试过使用syncwait.for,但var config 仍然返回一个空对象。

当需要/返回 config.js 时,我如何确保 var config aka (module.exports) 已完全填充。

【问题讨论】:

  • 不可能。重新考虑您的模块架构。提示:喜欢 jQuery ninja 模式并为您的模块提供一种.ready() 功能。它导出类似.init(callback) 的内容,允许您在异步功能完成后使用该模块。

标签: javascript node.js npm require


【解决方案1】:

npm.load 在其回调函数之前很长时间返回,因此在您使用console.log 打印它之后 设置了module.exports.globalModules。 您可以使用setTimeout() 设置一些延迟,以便及时完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 2022-01-24
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多