Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
-3
rated 0 times [  0] [ 3]  / answers: 1 / hits: 12277  / 10 Years ago, sat, june 21, 2014, 12:00:00

I use node.js on my server and I use redis key-store for storing data about my characters. Every connection has it own character. I want to get all data about characters(Person, has its name, age, profession, ...) into Characters array, so I can then selectively send it to connected clients.



var Characters = [];
for (var ID in Connections) {
redis_client.HGETALL(ID, function(err, result) {
if (result) {
Characters.push(result);
}
});
}
console.log(Characters);


I have read, that this is due to asynchronous vs synchronous problem, so I made global variable character.



//global variables
var character;
//function code
var Characters = [];
for (var ID in Connections) {
redis_client.HGETALL(ID, function(err, result) {
character = result;
});
if(character) {
console.log(character); // returns correct result
// make copy of character
Characters.push(JSON.parse(JSON.stringify(character)));
character = undefined;
}
}
console.log(Characters); // array of 1 character * number of connection
//BUT I expect different character for each connection

More From » node.js

 Answers
2

there are different ways,



the easiest way would be creating calling the async function one after another, as follows



    var Characters = [];
var objectKeys = Object.keys(Connections);
var ID = 0;
if (ID < objectKeys.length)
doCall(objectKeys[ID]);
else
console.log(Characters);
function doCall(key) {

redis_client.HGETALL(key, function(err, result) {
if (result) {
Characters.push(result);
}
ID++;
if ( ID < objectKeys.length)
doCall(objectKeys[ID]);
else
console.log(Characters);
});
}

[#44409] Thursday, June 19, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
andreguym

Total Points: 125
Total Questions: 112
Total Answers: 103

Location: Wallis and Futuna
Member since Tue, Mar 30, 2021
3 Years ago
;