【发布时间】:2015-08-19 10:59:13
【问题描述】:
我在节点服务器中有这样的 Express 路由(需要文件):
var redis = require('../modules/redis');
module.exports = function (app) {
var redisClient = redis.init();
app.post('/auth/ticket', cors(), function (req, res) {
var hashes = ['hash1','hash2', 'hash3'];
var candidates = []; // An array to collect valid hashes
var key;
// to check each hash against a RedisDB I use a For Loop
for (key in hashes) {
var hash = hashes[key];
console.log("Hash " + hash + " will be proofed now:");
//now I try to collect the valid hashes in the candidates array
if (redisClient.exists(hash) === 1) candidates.push(hash);
}
console.log(JSON.stringify(candidates));
});
};
现在这是我的模块的代码,它将管理所有 redis 请求:
exports.init = function () {
Redis = exports.Redis = function () {
var promiseFactory = require("q").Promise,
redis = require('promise-redis')(promiseFactory);
this.client = redis.createClient();
this.client.on('error', function (err) {
console.log('redis error – ' + client.host + ':' + client.port + ' – ' + err);
});
Redis.prototype.exists = function (key) {
this.client.exists(key, function (err, data) {
return data === 1 ? true : false;
});
};
return new Redis();
};
所以我的经验是该模块能够正确地控制台记录结果。如果哈希有效,则返回 true,否则返回 false。这按预期工作。 问题是,for 循环在没有获取结果的情况下连续执行。我认为这是由竞争条件引起的。
如您所见,我已经开始在代码顶部使用 Q 和 promise-redis 来锻炼一些东西:
var promiseFactory = require("q").Promise,
redis = require('promise-redis')(promiseFactory);
this.client = redis.createClient();
我想知道,我如何让我的 for 循环(在 Express 路由中)等待 redisClient.exists(hash) 的结果,或者换句话说,将所有有效的哈希值放入我的候选数组中。
请帮忙
【问题讨论】:
-
你可以使用你的 Promise 库的
all()函数。这将同时查找它们并在完成后返回结果。请注意,如果您需要查找很多内容,这可能会给 Redis 带来很大的负担。 -
这也是我的情况。我需要平均查找 1 到 12 个哈希值。它是一个负载平衡系统。但我不知道如何正确实现它。在这种情况下,我从未使用过 promise it。
-
也许你可以给我代码示例,你将如何处理这个案例。只需一步,我就可以开发它。
标签: javascript node.js redis promise q