提供Promise作为模块的导出是Node.js中异步初始化的有效模式吗? [英] Is providing a Promise as a module's export a valid pattern for asynch initialization in Node.js?

查看:83
本文介绍了提供Promise作为模块的导出是Node.js中异步初始化的有效模式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一些加载数据的模块,然后提供该数据的接口。我想异步加载数据。我的应用程序已经使用了promises。是否要求模块使用有效的模式/习惯用语?

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?

示例模块:

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

示例用法:

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

更新:

我用过这已经有一段时间了,而且效果很好。我已经学到的一件事,它在接受的答案中暗示的是,缓存承诺本身是好的,每当你想访问数据时,使用然后 。第一次访问数据时,代码将一直等到promise被解决。随后使用然后将立即返回数据。例如。

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 then will return the data immediately. e.g.

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


推荐答案

对于模块来说,这似乎是一个非常好的界面工作是一次性获取一些数据。

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.

就我个人而言,我不确定为什么你需要 getId() getName()当你可以提供对属性的直接访问时,这些方法可以正常工作。

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.

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

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

这篇关于提供Promise作为模块的导出是Node.js中异步初始化的有效模式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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