The "big picture" is that any I / O is not blocked and runs asynchronously in your JavaScript; therefore, if you search databases, read data from a socket (for example, on an HTTP server), read or write files to disk, etc., you must use asynchronous code. This is necessary because the event loop is a single thread, and if I / O was not non-blocking, your program paused during execution.
You can structure your code so that there is less nesting; eg:
var fs = require('fs'); var mysql = require('some_mysql_library'); fs.readFile('/my/file.txt', 'utf8', processFile); function processFile(err, data) { mysql.query("INSERT INTO tbl SET txt = '" + data + "'", doneWithSql); } function doneWithSql(err, results) { if(err) { console.log("There was a problem with your query"); } else { console.log("The query was successful."); } }
There are also flow control libraries such as async (my personal choice) to avoid a lot of nested callbacks.
You may be interested in this screencast that I created on this subject .
source share