【发布时间】: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})
});
我已阅读此处的所有异步/同步回调问题,并尝试使用同步包解决此问题,但失败了。我尝试过使用sync 和wait.for,但var config 仍然返回一个空对象。
当需要/返回 config.js 时,我如何确保 var config aka (module.exports) 已完全填充。
【问题讨论】:
-
不可能。重新考虑您的模块架构。提示:喜欢 jQuery ninja 模式并为您的模块提供一种
.ready()功能。它导出类似.init(callback)的内容,允许您在异步功能完成后使用该模块。
标签: javascript node.js npm require