Node.js Asynchronous programming Code example


Example

Question: What is the output of code below and why?

setTimeout(function() {
    console.log("A");
}, 1000);

setTimeout(function() {
    console.log("B");
}, 0);

getDataFromDatabase(function(err, data) {
    console.log("C");
    setTimeout(function() {
        console.log("D");
    }, 1000);
});

console.log("E");

Output: This is known for sure: EBAD. C is unknown when it will be logged.

Explanation: The compiler will not stop on the setTimeout and the getDataFromDatabase methodes. So the first line he will log is E. The callback functions (first argument of setTimeout) will run after the set timeout on a asynchronous way!

More details:

  1. E has no setTimeout
  2. B has a set timeout of 0 milliseconds
  3. A has a set timeout of 1000 milliseconds
  4. D must request a database, after it must D wait 1000 milliseconds so it comes after A.
  5. C is unknown because it is unknown when the data of the database is requested. It could be before or after A.