如何在nodejs中异步要求 [英] How to async require in nodejs

查看:44
本文介绍了如何在nodejs中异步要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 bluebird 来初始化各种类型的数据库连接.

I'm using bluebird to init various type of db connections.

// fileA.js
Promise.all(allConnectionPromises)
    .then(function (theModels) {
        // then i want to do module.exports here
        // console.log here so the expected output
        module.exports = theModels
    })

这样我就可以从另一个文件中要求上面的文件.但是,如果我这样做,我会得到 {}.

So that I can require that file above from another file. however if I do that, i get {}.

let A = require('./fileA')  // i get {} here

知道怎么做吗?

推荐答案

在 Javascript 中,您无法神奇地将异步操作变成同步操作.因此,异步操作将需要异步编码技术(回调或承诺).常规编码和模块启动/初始化中的情况相同.

You can't magically make an async operation into a synchronous operation in Javascript. So, an async operation will require async coding techniques (callbacks or promises). The same is true in regular coding as in module startup/initialization.

处理这个问题的常用设计模式是给你的模块一个构造函数,你将回调传递给它,当你调用那个构造函数时,它会在异步结果完成时调用回调,然后是任何进一步的代码使用该异步结果的必须在该回调中.

The usual design pattern for dealing with this issue is to give your module a constructor function that you pass a callback to and when you call that constructor function, it will call the callback when the async result is done and then any further code that uses that async result must be in that callback.

或者,由于您已经在使用 Promise,您可以只导出调用代码可以使用的 Promise.

Or, since you're already using promises, you can just export a promise that the calling code can use.

// fileA.js
module.exports = Promise.all(allConnectionPromises);

然后,在使用它的代码中:

Then, in code that uses this:

require('./fileA').then(function(theModels) {
    // access theModels here
}, function(err) {
    console.log(err);
});

注意,当这样做时,导出的 promise 也可以作为 theModels 的方便缓存,因为每个其他模块都执行 require('./fileA')将获得相同的承诺,从而获得相同的解析值,而无需重新执行获取模型背后的代码.

Note, when doing it like this, the exported promise serves as a convenient cache for theModels too since every other module that does require('./fileA') will get the same promise back and thus the same resolved value without re-executing the code behind getting the models.

虽然我认为 promises 版本可能更简洁,尤其是因为您已经在模块中使用了 promises,但为了比较,这里是构造函数版本的样子:

Though I think the promises version is probably cleaner especially since you're already using promises within the module, here's what the constructor version would look like for comparison:

// fileA.js
var p = Promise.all(allConnectionPromises);

module.exports = function(callback) {
   p.then(function(theModels) {
       callback(null, theModels);
   }, function(err) {
       callback(err);
   });
}

然后,在使用它的代码中:

Then, in code that uses this:

require('./fileA')(function(err, theModels) {
    if (err) {
        console.log(err);
    } else {
        // use theModels here
    }
});

这篇关于如何在nodejs中异步要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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