Examples:
function test() {
console.log('function test()');
}
test();
console.log('end example.');
/* Will print:
* function test()
* end example.
*/
In the above code example we see a synchronous execution. To get into more details of what is
happening, look at the following figure:
function test() {
console.log('function test()');
}
setTimeout(test, 1000);
console.log('end example.');
/* Will print:
* end example.
* function test()
*/
To get into more details of what is happening, look at the following figure: Async code example mixing setTimeout and promises :
function test() {
console.log('function test()');
}
window.setTimeout(test, 0);
// Code in normal notation:
//var promise = new Promise(function(resolve, reject) {
// var i = 0;
// resolve('promised resolved.');
//});
//promise.then(/*resolve func*/ function(param) {console.log(param)},
// /*reject func*/ function(param) {console.log(param)});
// Same code as above, but in fat arrow notation:
var promise = new Promise((resolve, reject) => {
var i = 0;
resolve('promised resolved.');
});
promise.then(/*resolve func*/ param => console.log(param),
/*reject func*/ param => console.log(param));
// we could have skipped the reject function argument from above as it is not used.
console.log('end example.');
// Output:
// end example.
// promised resolved.
// function test()
Please do note that in the above example the Promise is executed
before setTimeout() even though setTimeout() comes before the Promise in the code and the delay
of setTimeout() is zero (i.e. no delay).The explaination for this is that promises are not placed
on the task queue, but they are placed on another queue (i.e. microtask queue) and are taken from this
queue as soon as they are resolved or rejected (the runtime does not wait until the calling stack is empty).