Blog

Basic Examples of Asynchronous Function Using Node.js
Posted on September 22, 2020 in JavaScript, Node.js by Matt Jennings

Running Code Asynchronously

The console.log(number3) code, which outputs the text of the number3.txt file below that is in the same directory as the JavaScript file which the code represents, is inside a callback function assigned to callback.

This function named callback is then passed in to the fs.readFile() method call as a callback function and the fs.readFile() method is an asynchronous, or non-blocking function. So the print4() function call is invoked before the fs.readFile() method call.

So if the number3.txt file contains the text 3, and the JavaScript file is named print-4-numbers.js that contains the code below, the executing the print-4-numbers.js file using Node (like node print-4-numbers.js) outputs:

1
2
4
3

print-4-numbers.js JS File Code

function print1() {
    const number1 = 1;
    console.log(number1);
}


function print2() {
    function getNumber2() {
        return 2;
    }
    // Blocking function call below
    const number2 = getNumber2();
    console.log(number2);
}


function print3() {
    const fs = require('fs');
    /*
    1.
    Reading data from a file is a non-blocking call, 
    which is shown below
    in the "number3" parameter below which 
    refers to the "number3.txt" file text, from the fs.readFile() method,
    and is an asynchronous functiona and passed into a callback function.

    2. The callback function below is an asynchronous function and is executed
    after all the synchronous, blocking function calls such as:
    print1();
    print2();
    print4();
    */
    fs.readFile('./number3.txt', 'utf-8', function (err, number3) {
        console.log(number3);
    });
}


function print4() {
    const number4 = 4;
    console.log(number4);
}

/*
Prints 3 last because it's invoked in an asynchronous function callback:
1
2
4
3
*/
print1();
print2();
print3();
print4();

 

Making Code Appear Synchronously, by Calling a Synchronous Function in an Asynchronous Function

function print1() {
    const number1 = 1;
    console.log(number1);
}


function print2() {
    function getNumber2() {
        return 2;
    }
    const number2 = getNumber2();
    console.log(number2);
}


function print3() {
    const fs = require('fs');
    const callback = function (err, number3) {
        console.log(number3);
        // invoked print4 function
        // to ensure that the console.log inside
        // of the print4 function is called
        // in the asynchronous callback function
        print4();
    };
    fs.readFile('./number3.txt', 'utf-8', callback);
}


function print4() {
    const number4 = 4;
    console.log(number4);
}

/* 
Prints 3 as second to last because
print4 function is invoked inside the "callback" function 
that is invoked as a parameter in the fs.readFile() method,
which itself is asynchronous:
1
2
3
4
*/
print1();
print2();
print3();

Leave a Reply