javascript 提供 Promise 作为模块的导出是否是 Node.js 中异步初始化的有效模式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32774491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:44:46  来源:igfitidea点击:

Is providing a Promise as a module's export a valid pattern for asynch initialization in Node.js?

javascriptnode.jspromisenode-modules

提问by Tony

I need to write some modules that load data one time and then provide an interface to that data. I'd like to load the data asynchronously. My application already uses promises. Is providing a promise as the result of requiring a module a valid pattern/idiom?

我需要编写一些一次性加载数据的模块,然后为该数据提供一个接口。我想异步加载数据。我的应用程序已经使用了 Promise。作为要求模块有效模式/习惯用法的结果提供承诺吗?

Example Module:

示例模块:

var DB = require('promise-based-db-module');

module.exports =
  DB.fetch('foo')
  .then(function(foo){
    return {
        getId: function(){return foo.id;},
        getName: function(){return foo.name;}
    };
  });

Example Usage:

示例用法:

require('./myPromiseModule')
.then(function(dataInterface){
  // Use the data
});

UPDATE:

更新:

I've used this for a while now and it works great. One thing I've learned, and it's hinted at in the accepted answer, is that it is good to cache the promise itself, and whenever you want to access the data use then. The first time the data is accessed, the code will wait until the promise is resolved. Subsequent usage of thenwill return the data immediately. e.g.

我已经使用了一段时间了,效果很好。我学到的一件事是,在接受的答案中暗示了这一点,那就是缓存承诺本身是很好的,并且无论何时您想访问数据都使用then. 第一次访问数据时,代码将等待,直到 promise 被解析。后续使用then将立即返回数据。例如

var cachedPromise = require('./myPromiseModule');
cachedPromise.then(function(dataInterface){
  // Use the data
});
...
cachedPromise.then(function(dataInterface){
  // Use the data again somewhere else.
});

采纳答案by jfriend00

This seems like a perfectly good interface for a module who's job is to do a one-time fetch of some data.

对于负责一次性获取某些数据的模块来说,这似乎是一个非常好的接口。

The data is obtained async so a promise makes sense for that. The goal is to fetch the data just once and then let all places this module gets used just have access to that original data. A promise works great for that too because it's a one-shot device that remembers its state.

数据是异步获取的,因此承诺是有意义的。目标是只获取一次数据,然后让所有使用该模块的地方都可以访问原始数据。Promise 对此也很有用,因为它是一种记住其状态的一次性设备。

Personally, I'm not sure why you need the getId()and getName()methods when you could just offer direct access to the properties, but either can work.

就我个人而言,当您可以提供对属性的直接访问时,我不确定为什么需要getId()getName()方法,但两者都可以工作。

A downside to this interface is that there is no means of requesting a fresh copy of the data (newly loaded from the DB).

此接口的缺点是无法请求数据的新副本(从数据库中新加载)。