Asynchronicity - A Node.js Pillar

At the foundation of Node.js asynchronicity is a fundamental issue. Non blocking code means that you as a programmer set acticvities in motion, and push on. If some of the activities are slow, we create a callback function to deal with the results of the started activities when they are ready to be dealt with.

Disk activities are much slower than memory activities in a computer. This means that you may start an activity such as a file, or database read, and push on with the following statements of your code. When the results of the read are ready, they are sent to the callback function that was waiting for them. This utilizes the computer resources optimally when activities happen in parallel.

Here is a brief example illustrating how this is done, and then we shall look at the Node.js file system module that utilizes this technique.

Asynchronicity in Practice

Example 15.16. An Asynchronous function, and the Call for it. asynchSample.js
/*
 * asynchronicity - as in Node
 */

/*
 * the asynch function
 */
const find = function(param1, param2) {     // asynchronous function, could be db query
    process.nextTick(function() {           // process.nextTick makes it asynch
        let err = false;
        let data = 0;
        try {                               // do something that takes time
            for (let i = 0; i < param1; i++) {
                let flip = Math.floor(Math.random() * 2);   // flip coin
                data += flip;                               // count ones
            }
        } catch (e) {
            err = true;
        }
        param2(err, data);                  // param2 is a function, aka callback
    });
}


/*
 * program flow
 */
find(1000000000, function(err, data) {      // execute the asynch function
    if (err) {                              // with callback definition
        console.log("error");
    }
    console.log(data);                      // response from async callback
});
console.log("next statement");              // next sequential statement

And its execution

$ node asynchSample
next statement
500001251