2016-08-04 81 views
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}) 
}); 

我看了所有的异步/同步回调的问题在这里,并试图通过使用同步方案,但都未能解决这个问题。我曾尝试使用syncwait.for,但var config仍然返回空对象。

如何确保var config又名(module.exports)在需要/返回config.js时完全填充。

+0

这是不可能的。重新思考你的模块体系结构。提示:像jQuery忍者模式一样,并为你的模块提供一种'.ready()'函数。它导出类似'.init(callback)'的东西,它允许你在异步函数完成后使用模块。 – slebetman

回答

0

npm.load回报长的回调函数之前,所以module.exports.globalModules设置你以后再console.log打印。 您可以使用setTimeout()设置一些延迟,以便及时完成。