0
这是我目前经历的一个简化例子。只返回module.exports一次npm.load回调返回
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
仍然返回空对象。
如何确保var config
又名(module.exports
)在需要/返回config.js
时完全填充。
这是不可能的。重新思考你的模块体系结构。提示:像jQuery忍者模式一样,并为你的模块提供一种'.ready()'函数。它导出类似'.init(callback)'的东西,它允许你在异步函数完成后使用模块。 – slebetman