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

时间:2016-02-10 14:19:47

标签: javascript promise bluebird

虽然我已经知道了很长一段时间的承诺,但我最近才开始使用它们(或创建它们)。

我的要求是创建一个promise promise函数,以便调用者可以调用然后将其链接到其他函数调用。

像这样的简单函数......

/**
 *  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,以获得包含承诺的函数对象。

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

或者还有其他方法吗?或者,是否存在编写承诺兼容代码的本地方式?

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

1 个答案:

答案 0 :(得分:0)

使用适当的promise API。

鉴于 var ipEndPoint = new IPEndPoint(IPAddress.Parse(exit.Address), 80); 已经是一个承诺返回函数,没有理由宣传hgetAllAsync甚至使用chkUserInCache构造函数。相反,您应该删除Promise回调并返回承诺:

done
相关问题