【问题标题】:How to async require in nodejs如何在nodejs中异步需求
【发布时间】:2016-01-23 10:00:47
【问题描述】:

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

// 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
    })

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

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

知道怎么做吗?

【问题讨论】:

  • 你的参数符合promise.all是prmises数组吗?
  • 请检查promise 是否正确执行?
  • @null1941 是的。当我使用 console.log 时,我得到了预期的输出。
  • 你能发布更多代码来查看吗?
  • 你不能在异步方法中导出

标签: node.js promise


【解决方案1】:

您不能在 Javascript 中神奇地将异步操作变成同步操作。因此,异步操作将需要异步编码技术(回调或承诺)。在常规编码中与在模块启动/初始化中也是如此。

处理此问题的常用设计模式是为您的模块提供一个构造函数,您将回调传递给该构造函数,当您调用该构造函数时,它将在异步结果完成时调用回调,然后再调用任何其他代码使用该异步结果的必须在该回调中。

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

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

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

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

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


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

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

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

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

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

【讨论】:

  • 嗨,这会使使用它变得非常困难。最好,如果可能的话,我想要像var models = require('./models') 这样的东西。
  • @TuanAnhTran - 正如我在回答中已经说过的那样,您无法同步获取异步值。你就是不能。在 node.js 中学习编程的一部分是学习使用异步 IO 进行编程,以及如何高效、干净地进行编程。在这种情况下,您将需要这样做。这通常意味着更改内容以将您希望在 require() 语句之后的代码移动到传递数据的回调内部。这就是您使用异步结果进行编程的方式。欢迎来到 node.js 编程的异步世界。
猜你喜欢
  • 2016-06-25
  • 1970-01-01
  • 2019-01-21
  • 2017-12-16
  • 2016-12-14
  • 2014-03-28
  • 2018-01-15
  • 2021-03-03
  • 2017-05-15
相关资源
最近更新 更多