[英]How do I Promisify an Async operation, using the Async library?
GrabRedisDataByArray = Promise.promisify(function(data, callback) {
var temp_results = [];
async.each(data, function(result, done) {
redis.hgetall('username:' + result, function(err, results) {
temp_results.push(results);
done();
})
}, function(err) {
callback(temp_results)
});
});
Except, it's returning 除了,它回来了
Unhandled rejection (<[{"server":"9300","user_id":"31","char...>, no stack trace )
--That object data is just some user information stored in the username:
key. -对象数据只是存储在
username:
键中的一些用户信息。
And my method for data retrieval is: 我的数据检索方法是:
GrabRedisDataByArray(data).then(function(data){
console.log(data)
});
I think my problem is with GrabRedisDataByArray
and how it doesn't return anything in the main function scope, but only returns something through its second parameter? 我认为我的问题出在
GrabRedisDataByArray
,它如何在主函数范围内不返回任何内容,而仅通过其第二个参数返回什么? If that makes sense? 那有道理吗? I'm just kind of lost here and trying to understand how I can return that async operation to the main function instead of only returning it through the second parameter callback (Which is I think my promises isn't working correctly)
我在这里有点迷失,试图了解如何将异步操作返回到主函数,而不是仅通过第二个参数回调返回(这是我认为我的诺言无法正常工作)
Edit: This is using the Bluebird library 编辑:这是使用蓝鸟库
Well, promisify
expects node-style callbacks, so when you're calling callback(temp_results)
you are passing an error parameter. 好吧,
promisify
需要节点样式的回调,因此,当您调用callback(temp_results)
您将传递一个error参数。 It would have to be callback(null, temp_results)
. 它必须是
callback(null, temp_results)
。
That said, you should not use the async
library at all when you're working with promises anyway. 就是说,无论如何在使用
async
时都不应该使用async
库。 Just embrace promises. 只是信守承诺。 Or if you insist on using
async
, at least do it properly: 或者,如果您坚持使用
async
,至少请正确执行以下操作:
var grabRedisDataByArray = Promise.promisify(function(data, callback) {
async.map(data, function(result, done) {
redis.hgetall('username:' + result, done);
}, callback);
});
But when promisifying, you should always promisify on the lowest level - in your case redis
. 但是,在进行承诺时,应该始终在最低级别进行承诺-在您的情况下为
redis
。 Then you don't have to mess around with async
callbacks but can simply use Bluebird's Promise.map
: 然后,您不必弄乱
async
回调,而只需使用Bluebird的Promise.map
:
Promise.promisifyAll(redis);
function grabRedisDataByArray(data) {
return Promise.map(data, function(result) {
return redis.asyncHgetall('username:' + result);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.