I have an array like this:
var names = ['Irina', 'Michael', 'Carl'];
I want to insert them into redis using transactions with promises (I don't know another way). But I'am confused about how to do this; this is my code:
var Promise = require("bluebird");
var redis = require("redis");
Promise.promisifyAll(redis.RedisClient.prototype);
Promise.promisifyAll(redis.Multi.prototype);
var client = redis.createClient(), multi;
var names = ['Irina', 'Michael', 'Carl'];
var result = names.map(function(item) {
client.watch('user:id');
client.getAsync('user:id', function(err, data) {
var multi = client.multi();
var user_id = parseInt(data) + 1;
multi.hmsetAsync('user:' + user_id, 'username', item, 'about', 'love to coding');
multi.incrAsync('user:id');
multi.execAsync(function(err,data){
console.log(data);
});
});
});
Promise.all(result).then(function(response) {
console.log(response);
});
But this does not works (:
EDIT: This is the error thrown by the application:
Unhandled rejection Error: ERR wrong number of arguments for 'get' command
Someone, could help me please !
EDIT 2: I have change my code, but now only saves the last value of the array:
client.watch('user:id');
var result = names.map(function(item) {
var multi = client.multi();
client.getAsync('user:id').then(function(value) {
var user_id = parseInt(value) + 1;
return user_id;
}).then(function(user_id) {
multi.hmsetAsync('user:' + user_id, 'username', item, 'about', 'love to coding');
multi.incrAsync('user:id');
}).then(function() {
multi.execAsync().spread(function(err,data){
console.log(data);
});
});
});
EDIT 3:
When using redis' MONITOR
, this is the output:
[0 127.0.0.1:54439] "info"
[0 127.0.0.1:54439] "watch" "user:id"
[0 127.0.0.1:54439] "get" "user:id"
[0 127.0.0.1:54439] "get" "user:id"
[0 127.0.0.1:54439] "get" "user:id"
[0 127.0.0.1:54439] "MULTI"
[0 127.0.0.1:54439] "hmset" "user:88" "username" "Irina" "about" "love to coding"
[0 127.0.0.1:54439] "incr" "user:id"
[0 127.0.0.1:54439] "EXEC"
[0 127.0.0.1:54439] "MULTI"
[0 127.0.0.1:54439] "hmset" "user:88" "username" "Michael" "about" "love to coding"
[0 127.0.0.1:54439] "incr" "user:id"
[0 127.0.0.1:54439] "EXEC"
[0 127.0.0.1:54439] "MULTI"
[0 127.0.0.1:54439] "hmset" "user:88" "username" "Carl" "about" "love to coding"
[0 127.0.0.1:54439] "incr" "user:id"
[0 127.0.0.1:54439] "EXEC"
Executes the get user:id
3 times, and then the others methods. Why?