从回调返回顶级函数的值

时间:2015-12-09 21:54:56

标签: javascript node.js callback

尝试导出由函数创建的值,并且只能通过回调访问。不知道如何处理这个问题。

require("lib").doThing("thing", function(value) {
    // need to get value to the top level in order to export it
});

module.exports = value;

4 个答案:

答案 0 :(得分:0)

如果doThing是同步的,这将有效:

require("lib").doThing("thing", function(value) {
    module.exports = value;
});

如果它是异步的,您必须导出一个对象,然后在回调触发时改变对象上的属性:

require("lib").doThing("thing", function(value) {
    module.exports.value = value;
});

module.exports = {};

答案 1 :(得分:0)

在带回调的函数中包装,导出整个函数:

function getValue(callback) {
    require("lib").doThing("thing", function(value) {
        // need to get value to the top level in order to export it
        callback(value);
    });
}

module.exports.getValue = getValue;

然后致电:

exportedVar.getValue(function(val) {
    console.log(val);
});

答案 2 :(得分:0)

没有理由让它达到顶级水平。只要在回调中包含值或导出promise时输出它:

require("lib").doThing("thing", function(value) {
    // need to get value to the top level in order to export it
    module.exports = value;
});

如果上面的上述回调是异步的,那么您将遇到时间问题,因为加载您的模块的人无法准确获取该属性,直到完成异步功能并且他们不知道当确切的时间是。

有很多方法可以解决这个问题,但一种很好的方法是导出一个promise而不是value。然后,呼叫者可以在承诺上调用.then()来获取值。

module.exports = new Promise(function(resolve) {
    require("lib").doThing("thing", function(value) {
        // need to get value to the top level in order to export it
        resolve(value);
    });
});

然后,这个模块的调用者会做这样的事情:

require('someModule').then(function(value) {
    // process the value here
});

答案 3 :(得分:-1)

目前还不清楚你要做什么,但你总是可以从匿名函数中返回一个值。

module.exports = require("lib").doThing("thing", function(value) {
    // need to get value to the top level in order to export it
    return value;
});
相关问题