Problem:
I needed to create a node application that would ping a list
of servers and return their status (if are they up or down). All seemed easy enough until I needed to
create asynchronous calls within a “for loop”.
The async method’s callback contained logic to simply build and return another
object with the result data. Unfortunately, I couldn’t get ANY data back.
Research:
After poking around some blogs and chatting with a coworker,
I learned about node’s infamous “queue” of processes which fires AFTER my code
finishes execution. That is, when my “for
loop” makes the async calls (let’s say, 5 times), the callback doesn’t fire
until the end of my code is reached. Here’s what I initially coded:
“returnObj” was serialized and written to the DOM well
before the async callback was executed, writing a big, fat NOTHING to the browser. This confused me for hours. What I needed to
do was somehow write the response to the browser AFTER I get the data from the
callback.
Solution:
This was another problem a recursion method could resolve.
It’s probably not the most efficient, but it was fast enough for me.
Here’s the code:
I created a function called “probeit” accepting an array of
host names, the node response object, and a json object to return. I loaded the array with
host name before calling this function, and passed empty objects that will be
loaded during the recursion (res and returnObj).
Think of this as a process of elimination. We pass the hosts array, we splice the first
value, make an async call, and call the function within itself over and over
again until the array is empty. When the
array is empty, then stringify and write the object to the browser. WORKED!!
Hope this helps somebody.
Comments
Post a Comment