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

Ton*_*ony 27 javascript node.js promise node-modules

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

示例模块:

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;}
    };
  });
Run Code Online (Sandbox Code Playgroud)

用法示例:

require('./myPromiseModule')
.then(function(dataInterface){
  // Use the data
});
Run Code Online (Sandbox Code Playgroud)

更新:

我现在已经使用了一段时间了,效果很好.我已经学到的一件事,它在接受的答案中暗示的是,缓存承诺本身以及每当您想要访问数据时都是好的then.第一次访问数据时,代码将一直等到promise被解决.后续使用then将立即返回数据.例如

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

jfr*_*d00 11

对于模块来说,这似乎是一个非常好的接口,他的工作是一次性获取一些数据.

数据是异步获得的,因此承诺对此有意义.目标是只获取一次数据,然后让这个模块使用的所有地方只能访问原始数据.承诺对此也很有用,因为它是一个能够记住其状态的一次性设备.

就个人而言,我不确定为什么你需要这些getId()getName()方法,你可以直接访问属性,但任何一个都可以工作.

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