Node.js Asynchronous programming Code example


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

setTimeout(function() {
}, 1000);

setTimeout(function() {
}, 0);

getDataFromDatabase(function(err, data) {
    setTimeout(function() {
    }, 1000);


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.