ioredis
ioredis copied to clipboard
How to obtain results from pipeline without ugly indexing?
I find it difficult to get a good grip on results returned from pipelines. e.g: if I push 4 commands into a pipeline, then execute it, ioredis gives back an array in which I have to use an index to get the result from one of the commands.
To solve this problem I tried the callback approach, which seems to work:
let p = redis.pipeline() p.get('a', console.log); p.get('b', console.log); await p.exec();
HOWEVER:
let p = redis.pipeline();
p.get('a', console.log);
p.get('b', console.log);
p.multi().hset('h', {a:8, b:9}).hgetall('h', console.log).exec();
await p.exec();
this will output "QUEUED" for the HGETALL, which seems logical because the result is aggregated in the EXEC. so I tried:
let p = redis.pipeline();
p.get('a', console.log);
p.get('b', console.log);
p.multi().hset('h', {a:8, b:9}).hgetall('h').exec(console.log);
await p.exec();
Code above replies with 2 values for both GET commands plus 1 value containing a raw Buffer, which seems odd. The biggest problem here is that the result from the MULTI is again hard to attach to the initial command.
So I did:
var c = [
['set', 'a', 8],
['set', 'b', 3],
['get', 'b', console.log],
['hmset', 'h', 'a', 1, 'b', 2],
['hgetall', 'h', console.log],
['multi', [
['get', 'a', console.log],
['get', 'b'],
['hgetall', 'h', console.log]
]]
];
c = c.reduce(function(c, v) {
if (v[0] === 'multi') {
c.push(['multi']);
c.push(...v[1].map(x => 'function' === typeof x[x.length-1] ? x.slice(0, -1) : x));
c.push(['exec', function(s, r) {
r.forEach((x,i) => {
let t = v[1][i];
let f = t[t.length-1];
if ('function' === typeof f) f.call(this, s, x);
});
}]);
} else {
c.push(v);
}
return c;
}, []);
var p = r1.pipeline();
p.addBatch(c);
await p.exec();
Above code basically flattens the MULTI, hooks a callback to the EXEC that calls the original callback for the commands in the MULTI (if any). This looks like it is working, but the Buffer problem remains for all callbacks in the MULTI.
How can I retrieve a properly parsed result from the MULTI ????
Thanks!