2015-05-19 91 views
0

我正在使用此插件管理器https://github.com/c9/architect并创建一个节点模块。我遇到的问题是我想从我的节点模块公开api到主机应用程序。问题在于插件管理器使用回调来表示所有插件都已注册。Node.JS退回回调

例: 在我的主要应用程序,我要求我创建

var api = require('apiModule') 

在我node_modules目录

module.exports = (function apiModule(){ 

    architect.createApp(config, function(err, app){ 
     if(err) throw err; 

     return app 

    }); 

})(); 

这显然是行不通的我的API模块,但证明了我我试图将app的值返回给主应用程序。

我怎样才能将app的值返回到api变量?

回答

0

你没有通过回调,而是创建一个回调。 你的功能不应该自己执行。

你的代码应该是:

var architect = require('architect'); 
module.exports = function apiModule(config, callback){ 

    architect.createApp(config, callback); 

}); 

//otherModule 
var apiModule = require('apiModule'); 
var config = require('config'); 
apiModule(config, function(err, app){ 
    if(err) throw err; 

    // do something with app 
}); 

如果你正在寻找一个更地道的API来你已经习惯了的东西。 我建议你尝试bluebird

var architect = require('architect'); 
var Promise = require('bluebird'); 
var createApp = Promise.promisify(architect.createApp); 
module.exports = function apiModule(config) { 
    return createApp(config); 
} 

// Then in your other module 
var apiModule = require('apiModule'); 
apiModule() 
    .then(function(result) {}) 
    .catch(function(error) {}) 

我希望清除它:)

+0

第一模块中的功能将被执行当你需要('apiModule')'时立即失败,因此'callback'不会被定义。你必须删除'()' – Pierrickouw

+0

是的,在我清理代码之前,我很快就按下了输入。 – pixeleet

+0

你很快就会减去答案,但却懒得提供解决方案。礼貌。 – pixeleet

0

你可以回调传递给你的你的模块:

module.exports = function(callback){ 

    architect.createApp(config, function(err, app){ 
     if(err) throw err; 

     return callback(app); //you should check if callback is a function to prevent error 

    }); 

}); 

var api = require('apiModule'); 
api(function(app) { 
    console.log(app); //you access your app 

}) 
+0

是的,我想到了这一点,但你必须记住,我将为其他人提供这个模块。我不能让他们在我的回调中包装整个应用程序。我需要他们能够只需要()并能够使用它。即使他们不得不做第二步,也许共享变量将变得可用或什么的。 – Rob