Aller au contenu

Exercises related to Node.js

Synchronous vs. Asynchronous Programming

Exercice 1

Review the code examples from the Intro to Node.js codelab. Explain the differences between the two examples “taskA_taskB_noexit.js” and “taskB_callitself.js” in the way the call stack and the event loop behave. You must draw the call stack for both examples and explain what events will be queued for the Node.js event loop.

Solution

In “taskA_taskB_noexit.js”, taskB is scheduled to run on the EventQueue at regular intervals. In “taskB_callitself.js”, taskB calls itself in a recursive way, without delay. The program will thus produce a stack overflow error.

Asynchronous Programming

Exercice 2

Read the code below and explain what the output of program is:

console.log('<0> schedule with setTimeout in 1-sec');
setTimeout(() => console.log('[0] setTimeout in 1-sec boom!'), 1000);

console.log('<1> schedule with setTimeout in 0-sec');
setTimeout(() => console.log('[1] setTimeout in 0-sec boom!'), 0);

console.log('<2> schedule with setImmediate');
setImmediate(() => console.log('[2] setImmediate boom!'));

console.log('<3> A immediately resolved promise');
aPromiseCall().then(() => console.log('[3] promise resolve boom!'));

function aPromiseCall () {
  return new Promise(function(resolve, reject) {
    return resolve();
  });
}

Solution
<0> schedule with setTimeout in 1-sec
<1> schedule with setTimeout in 0-sec
<2> schedule with setImmediate
<3> A immediately resolved promise
[3] promise resolve boom!
[1] setTimeout in 0-sec boom!
[2] setImmediate boom!
[0] setTimeout in 1-sec boom!