javascript - Push object into local array from asynchronous callback function -
javascript - Push object into local array from asynchronous callback function -
i utilize node.js on server , utilize redis key-store storing info characters. every connection has own character. want info characters(person, has name, age, profession, ...) characters array, can selectively send connected clients.
var characters = []; (var id in connections) { redis_client.hgetall(id, function(err, result) { if (result) { characters.push(result); } }); } console.log(characters);
i have read, due asynchronous vs synchronous problem, made global variable character.
//global variables var character; //function code var characters = []; (var id in connections) { redis_client.hgetall(id, function(err, result) { character = result; }); if(character) { console.log(character); // returns right result // create re-create of character characters.push(json.parse(json.stringify(character))); character = undefined; } } console.log(characters); // array of 1 character * number of connection //but expect different character each connection
there different ways,
the easiest way creating calling async function 1 after another, 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); }); }
javascript node.js asynchronous redis
Comments
Post a Comment