异步模块的NodeJS出口 [英] Asynchronous nodejs module exports

查看:129
本文介绍了异步模块的NodeJS出口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在想,最好的办法是什么配置模块的出口。下面的async.function的例子可以是一个FS或HTTP请求,简化为示例的目的:

I was wondering what the best approach is for configuring a module export. "async.function" in the example below could be a FS or HTTP request, simplified for the sake of the example:

下面的例子code(asynmodule.js):

Here's example code (asynmodule.js):

var foo = "bar"
async.function(function(response) {
  foo = "foobar";
  // module.exports = foo;  // having the export here breaks the app: foo is always undefined.
});

// having the export here results in working code, but without the variable being set.
module.exports = foo;

我如何导出只有一次异步回调已经执行的模块?

How can I export the module only once the async callback has been executed?

修改
在我的实际使用情况的快速注:我正在写一个模块来配置nconf中( https://github.com/flatiron/nconf )在fs.exists()回调(例如,它会解析一个配置文件并设置nconf中)。

edit a quick note on my actual use-case: I'm writing a module to configure nconf (https://github.com/flatiron/nconf) in an fs.exists() callback (i.e. it will parse a config file and set up nconf).

推荐答案

您的出口无法工作,因为它是功能外,而声明在里面。但是,如果你把里面的出口,当你使用你的模块,你不能确定出口定义。

Your export can't work because it is outside the function while the foodeclaration is inside. But if you put the export inside, when you use your module you can't be sure the export was defined.

与ansync系统工作的最佳方法是使用回调。你需要导出一个回调分配方法来获取回调,并调用它的异步执行。

The best way to work with an ansync system is to use callback. You need to export a callback assignation method to get the callback, and call it on the async execution.

例如:

var foo, callback;
async.function(function(response) {
    foo = "bar"
    if (exists){
        foo = "foobar";
    }

    if( typeof callback == 'function' ){
        callback(foo);
    }
});

module.exports = function(cb){
    if(typeof foo != 'undefined'){
        cb(foo); // If foo is already define, I don't wait.
    } else {
        callback = cb;
    }
}

在主

var fooMod = require('./foo.js');
fooMod(function(foo){
    //Here code using foo;
});

这篇关于异步模块的NodeJS出口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆