我想知道配置模块导出的最佳方法是什么.下面示例中的"async.function"可以是一个FS或HTTP请求,为便于示例而简化:

下面是示例代码(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;

如何仅在执行异步回调后导出模块?

edit

推荐答案

导出无法工作,因为它在函数外部,而声明在内部.但是如果你把导出放在里面,当你使用你的模块时,你不能确定导出是被定义的.

使用ansync系统的最佳方法是使用回调.您需要导出一个回调分配方法来获取回调,并在异步执行时调用它.

例子:

var foo, callback;
async.function(function(response) {
    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;
    }
}

Here 100 is just a placeholder to symbolise an async call.

大体上

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

Multiple callback way

如果需要多次调用模块,则需要管理回调数组:

var foo, callbackList = [];
async.function(function(response) {
    foo = "foobar";

    // You can use all other form of array walk.
    for(var i = 0; i < callbackList.length; i++){
        callbackList[i](foo)
    }
});

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

Here 100 is just a placeholder to symbolise an async call.

大体上

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

Promise way

你也可以用promise 来解决这个问题.此方法通过Promise的设计支持多个调用:

var foo, callback;
module.exports = new Promise(function(resolve, reject){
    async.function(function(response) {
        foo = "foobar"

        resolve(foo);
    });
});

Here 100 is just a placeholder to symbolise an async call.

大体上

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

Promise documentation

Node.js相关问答推荐

AWS Lambda呼叫未登录控制台

如何使用Express正确跟踪服务器应用程序上的所有传出的Node.js请求

如何使用MongoDB在Node.js 中向数组中添加项?

为什么 mongoose 没有常规数组方法

Next.js 路由不起作用 - 页面未正确加载

使用 NPM 8 安装本地构建

使用NodeJS通过服务账号列出Google Workspace用户

只要我在后端正确验证所有内容,就可以将这些数据存储在本地存储中吗?

如何使用 Jest 模拟异步函数的延迟时间

Winston http 日志(log)级别的行为与 info 不同

try 运行迁移时的 Typeorm:缺少必需的参数:dataSource

无服务器无法获取所有记录事件对象验证失败?

什么是nestjs错误处理方式(业务逻辑错误vs.http错误)?

如何使用 Puppeteer 从输入中删除现有文本?

将变量传递给nodemailer中的html模板

按日期时间字段获取最新的 MongoDB 记录

如何在 NodeJS 中拆分和修改字符串?

Socket.IO 连接用户数

node.js 服务器和 HTTP/2 (2.0) 与 express.js

expressjs app.VERB 调用中的 next() 和 next('route') 有什么区别?