函数返回一个函数的值

import.js

exports.getConfig = function() { return api.getConfig(); }; 

test.js

 // Aanmaken lightBridge obj = reflector.getObj(); console.log(obj); // Toon alle lichten obj.getConfig().then(function(config) { console.log(config); }).done(); 

在最后一个片段中,它使用了当我调用getConfig()的函数,我想要在variablesconfiguration中的输出。 现在的问题是,当我想logging我收到的variablestesting未定义。

如果我console.log(config)而不是返回configuration; 它完美的作品。 看起来很奇怪。

当我想使用它的结果就像varia.getConfig()=> config的输出。

testing只存在于你的function不在外面。 你可以尝试这样的东西,但它可能很脏。

  var test; exports.getConfig = function() { api.getConfig(function(err, config) { if (err) throw err; test = config; }); 

听起来就像你正试图消耗一个asynchronous函数,就好像它是同步的。 你不能这样做。 你可以做的是从getConfig返回一个承诺。

 exports.getConfig = function() { return api.getConfig(); }; 

那么你的模块可以像这样消耗:

 const myModule = require('my-module'); myModule.getConfig().then(function(config) { console.log(config); }); 

从评论听起来像你使用Express。 如果你想用Express来发送HTTP响应,你可以这样做:

 app.get('/config', function(request, response) { myModule.getConfig().then(function(config) { response.send(config); }); }); 
Interesting Posts