Skip to content

Instantly share code, notes, and snippets.

@shardulmohite
Last active August 29, 2015 13:56
Show Gist options
  • Save shardulmohite/f2956009a53d573f1e14 to your computer and use it in GitHub Desktop.
Save shardulmohite/f2956009a53d573f1e14 to your computer and use it in GitHub Desktop.
DNS look up , example of Non-Blocking function of JS .
var SiteArray = ['google.com','webonise.com','facebook.com','techcrunch.com','indiatimes.com'];
var dns = require('dns');
for(var i = 0 ; i < SiteArray.length ; i++){
dns.lookup(SiteArray[i],function(err,ip){
if (err) return handleError(err);
console.log( " %s resolved to %s ", SiteArray[i],ip );
});
}
Copy link

ghost commented Mar 3, 2014

Shardul,

Regarding large element in array what could be solution, I think problem remain same, I've tested above code with 15648 elements I got same issue.

When I dig more into this we all know JavaScript is Single thread programming language, and async callback or non blocking I/O works on event rather than threads or process because threads/process carry a heavy memory cost.(as Threads and process are heavier or system might not support many that much threads, this was one of reason why Nginx(event-based) become so popular than Apache(Thread or process-based on configuration) ).

So what happening behind the scene is follows :-

--Whole code runs in the main thread and main thread register async callback to event loop.(An event loop is “an entity that handles and processes external events and converts them into callback invocations”. ) At an I/O call, your code saves the callback and returns control to the node.js runtime environment. So for below line

for(var i = 0 ; i < SiteArray.length ; i++){
    dns.lookup(SiteArray[i],function(err,ip){
        if (err) return handleError(err);
        console.log( " %s resolved to %s ", SiteArray[i],ip );
    });
}

dns.lookup is register with event-loop, and execution return back to NodeJS runtime environment, this repeat with all element of array.

--After executing for loop NodeJS runtime proceed with executing other statement of function sequentially. so if you have written code below loop that has another loop that prints array you'll see that value before you started seeing callbacks console.log.

--After executing for loop or other part of code, and if any event occurred then you'll see execution of callbacks but while executing for loops any event occur on event-loop than callback will not be trigger because of Single thread and that thread is busy doing other job.

@vishaltelangre
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment