'NodeJS and Redis : getting three values simultaneously
currently I do this for getting many values in NodeJS and Redis with node-redis :
redis.get('data1', function(err, data1)
{
redis.get('data2', function(err, data2)
{
redis.get('data3', function(err, data3)
{
if (data3 == xx && data2 == xx && data3 == xx)
{
console.log('its ok');
}
});
});
});
The problem is that the three request will be one after another, I want to make 3 at once, and then call my condition like this for example (this don't work it's just for you understand what I want) :
redis.get('data1', function(err, data1) { var data1 = data1; });
redis.get('data2', function(err, data2) { var data2 = data2; });
redis.get('data3', function(err, data3) { var data3 = data3; });
// When the 3 get operations was finished
if (data3 == xx && data2 == xx && data3 == xx)
{
console.log('its ok');
}
Thank you in advance
Solution 1:[1]
MGET will probably be the fastest, instead of going back and forth 3 times:
client.mget(["data1", "data2", "data3"], function (err, res) {
console.dir(res);
});
Solution 2:[2]
One of the possible (but rather popular) ways is to use the async module like so:
async.map(['data1','data2','data3'], redis.get, function (err, results) {
if (err) { return; }
// results is now an array
});
Solution 3:[3]
Small update, maybe it will help someone avoid some frustration - in node-redis v4 some non-backwards compatible changes were implemented and, for example, .mget method has been changed to .mGet. See eg:
https://github.com/redis/node-redis/issues/1765
https://github.com/redis/node-redis/releases
Also now methods return Promises by default so async/await can be used instead of callbacks:
async testFunc() {
const values = ["first", "some", "second", "test", "third", "values"];
const mSetResult = await client.mSet(values);
console.log(mSetResult); // OK
const mGetResult = await client.mGet(["first", "second", "fourth", "third"]);
console.log(mGetResult); // [ 'some', 'test', null, 'values' ]
}
await testFunc();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ofir Luzon |
| Solution 2 | |
| Solution 3 | Zuku |
