Skip to main content

Posts

Showing posts from November, 2015

Node.js Looping and Async Calls: A Love Story

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 AFTE...