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.

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();
  });
}