4.2 Async Basics

Consider the following code

console.log('Starting app');
console.log('Finishing up');

No matter how many times you run the code, “Starting app” is always running before “Finishing up”.

To add some asynchronous code, we use setTimeout.

console.log('Starting app');
setTimeout(() => {
console.log("Inside of Callback");
}, 2000);
console.log('Finishing up');

Running the above, we get the below output.

$ node async-basics.js
Starting app
Finishing up
Inside of Callback

This is not what the code appears, but it is how the code is executed. (“Inside of Callback” is called after 2 seconds)

These 2 seconds did not stop the program from working, which is the key to non-blocking concepts.

Exercise

Write a 0-delayed timeout logging out after the first setTimeOut.

console.log('Starting app');
setTimeout(() => {
console.log("Inside of Callback");
}, 2000);
setTimeout(() => {
console.log("Inside of Callback 2");
}, 0);
console.log('Finishing up');

The output we get is

$ node async-basics.js
Starting app
Finishing up
Inside of Callback 2
Inside of Callback

This is strange because “Inside of Callback 2” is written before “Finishing up”, but this is perfectly expected. We will explain this next time.