Javascript 承诺/A-编写符合承诺的函数

Javascript 承诺/A-编写符合承诺的函数,javascript,promise,bluebird,Javascript,Promise,Bluebird,虽然我知道承诺已经有相当一段时间了,但我最近才真正开始使用(或创建)它们 我的要求是创建一个符合承诺的函数,以便调用方可以调用它,然后将它链接到其他函数调用 像这样的简单函数 /** * Checks if a user is available in cache. If avaialble, returns * the hash object of this user. If the cache is not enabled, or * the user is not foun

虽然我知道承诺已经有相当一段时间了,但我最近才真正开始使用(或创建)它们

我的要求是创建一个符合承诺的函数,以便调用方可以调用它,然后将它链接到其他函数调用

像这样的简单函数

/**
 *  Checks if a user is available in cache.  If avaialble, returns
 *  the hash object of this user.  If the cache is not enabled, or
 *  the user is not found in cache, it returns null object.
 *
 **/
function chkUserInCache(username, password, done) {
  var cacheKey = "partner:" + username;
  if (cache == null) return done(null);

  // Look for the user in the cache.
  cache.hgetallAsync(cacheKey).then(function(result){
    if (result === null) return done(null);
    else return done(null,result);
  });
}
调用函数的调用方式如下:

chkUserInCache(u,p)
.then(result) {
   // do something
}).catch(function(e){
  // do something
});
目前,我知道的一种方法是使用Bluebird promise,然后在我的函数上调用promisify,以获得一个与promise兼容的包装函数对象

但是,如果我有很多这样的函数(比如6到10个),我是否应该继续对每个函数调用promisifiy,并将返回的对象存储在某个位置并使用它

或者还有别的办法吗?或者,是否有编写符合承诺的代码的本地方法


对于<10个实用函数的简单用例,如果有,最好的方法是什么?

使用适当的promise API

鉴于
hgetAllAsync
已经是一个承诺返回函数,因此没有理由承诺
chkUserInCache
或者甚至使用
promise
构造函数。相反,您应该删除
done
回调,并返回承诺:

function chkUserInCache(username, password, done) {
  var cacheKey = "partner:" + username;
  if (cache == null) return Promise.resolve(null);

  // Look for the user in the cache.
  return cache.hgetallAsync(cacheKey);
}

是的,确切地说,我在寻找那种第三行,上面写着“return Promise.resolve(value);仍然有一些遗留问题试图将javascript承诺转化为c/c++/java背景:)