Promises/A - 编写一个符合承诺的函数
Promises/A - writing a function that complies with promises
虽然我知道 promises 已经有一段时间了,但我只是最近才真正开始使用它们(或创建它们)。
我的要求是创建一个符合 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,以获得包装的 promise 兼容函数对象。
但是如果我有很多这样的函数(比如 6 到 10 个),我是否应该继续对每个函数调用 promisifiy 并将返回的对象存储在某个地方并使用它?
或者还有其他方法吗?或者,是否有编写 promise 兼容代码的本机方法?
对于 < 10 个实用函数的简单用例,最好的方法是什么?
使用适当的承诺API。
鉴于 hgetAllAsync
已经是一个 promise-returning 函数,没有理由承诺 chkUserInCache
甚至使用 Promise
构造函数。相反,您应该删除 done
回调,只删除 return 承诺:
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);
}
虽然我知道 promises 已经有一段时间了,但我只是最近才真正开始使用它们(或创建它们)。
我的要求是创建一个符合 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,以获得包装的 promise 兼容函数对象。
但是如果我有很多这样的函数(比如 6 到 10 个),我是否应该继续对每个函数调用 promisifiy 并将返回的对象存储在某个地方并使用它?
或者还有其他方法吗?或者,是否有编写 promise 兼容代码的本机方法?
对于 < 10 个实用函数的简单用例,最好的方法是什么?
使用适当的承诺API。
鉴于 hgetAllAsync
已经是一个 promise-returning 函数,没有理由承诺 chkUserInCache
甚至使用 Promise
构造函数。相反,您应该删除 done
回调,只删除 return 承诺:
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);
}