Could someone try and help me to understand why the first function is non-blocking while the second one blocks the rest of the code? Isn't Promise.resolve the same as resolving from a new Promise? I can't quite wrap my head around it.
function blockingCode() {
return new Promise((resolve, reject) => {
for (let i = 0; i < 2500000000; i++) {
// Doing nothing...
}
resolve('ping');
});
}
function nonBlockingCode() {
return Promise.resolve().then(() => {
for (let i = 0; i < 2500000000; i++) {
// Doing nothing...
}
return 'pong';
});
}
console.time('non-blocking');
nonBlockingCode().then((message) => console.log(message));
console.timeEnd('non-blocking');
// console.time('blocking');
// blockingCode().then((message) => console.log(message));
// console.timeEnd('blocking');
The two functions are actually blocking.
You have the illusion that the second one isn't blocking because calling Promise.resolve().then() adds one more round to the event loop, so console.timeEnd('non-blocking'); is reached before the code inside your promise even starts.
You will notice that both function block if you fix your code like this:
console.time('non-blocking');
nonBlockingCode()
.then((message) => console.log(message))
.then(() => console.timeEnd('non-blocking'));
Note that a promise is intended not to block when the time-consuming logic inside the promise is delegated to a third-party, and you just wait for the result (e.g. when a client does a call to a remote database, a remote web server, etc.).
If you are having a hard time with promises and then logic, have a look at the async / await syntax, I find it much easier to understand.