2015-05-19 157 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