socket.io
keeps sending events to the server repeatedly until it gets an acknowledgement. Depending on the server load, acknowledgements might not be immediate. So multiple identical requests were being sent, and since async.parallel
uses a counter instead of individually tracking each function, the final function was getting prematurely called.
Javascript Async.js Parallel not working with socket.io
-
07-03-2022 - |
Question
I have the following block of code:
async.parallel([
function(cb){ module.rpc("user.data",{"username":data.username},cb); },
function(cb){ module.rpc("group.list",{"username":data.username},cb); },
function(cb){ module.rpc("set.list",{},cb); }
],function(error,result){
if(error){ callback(error); return; }
var user = result[0], groups = result[1], sets = result[2];
callback(null,template.render({"user":user,"groups":groups,"sets":sets}));
});
module.rpc
is a function that fetches the necessary data from the server via socket.io
. Now, the final function (async.parallel
's second argument) is supposed to be called only after the given 3 functions have called-back. However, during the template (EJS) rendering, when I try to access groups.data
, I sometimes get the error:
Uncaught TypeError: Cannot read property 'data' of undefined
The code seems perfectly fine to me, but works only occasionally. I have reloaded the page repeatedly, without changing the underlying code, and had a success rate of about 20%. I have absolutely no clue why things are going wrong here. All I can guess is that the assignment of that variable is delayed. And so I tried delaying the rendering using window.setTimeout
, but to no avail. Why is this happening? How do I fix it?
Solution