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');