I'm trying to fully understand the concepts of async and promises for more than a year, but I still can't grasp everything about it.
Most of the Promises docs are about 'non blocking' and example codes simulate long requests with a setTimeout along this way:
console.log('foo1');
let promiseA = new Promise(resolv => {
setTimeout(() => resolv('finished'), 1000);
})
promiseA.then(answer => {
console.log(answer);
});
console.log('foo2');
which yields to
"foo1"
"foo2"
"finished"
But isn't this mixing two different concepts at once ? As I understand, setTimeout functions are browser/runtime functions, setTimeout precisely triggering an internal counter in the browser thread, your callback function being re-added to the JavaScript engine at the end of the timeout through the macrotask queue, thus allowing your js below the call the function to still execute.
But what about examples where no setTimeout is used? Consider this:
let promiseA = new Promise(resolv => {
uselesscounter = 0;
for(let i = 0; i < 1000000000; i++) {
uselesscounter+= 1;
}
resolv('finished');
})
promiseA.then(answer => {
console.log(answer);
})
console.log('foo2')
From the top example, we might think that we are going to have "foo1", "foo2", then the loop will take time and we would have the "finished" a couple seconds later. It is not what is happening. As the executor code is executed directly (and not using any browser api) it is blocking the "foo2" underneath, despite in the end the resolving callback being added to the microtask queue and displayed after "foo2".
So, does a callback like that, which do not use browser api functions, make sense?
Promises are useful to use when waiting for some data or a signal of some kind from outside of the code itself, such as api calls and whatnot.
If your code is entirely self contained then there will be no performance gains using promises.
In your second example the code runs as expected, because promises don't execute "later". In a promise the code will keep on running until encountering an asynchronous operation that doesn't execute in the current context (thread, worker, etc..), when that happens it will not block while waiting for the result, but will run the lines following the promise until the result of the promise is requested (by using await for example), and when that happens your runtime will return the result of the promise if available, or block your program until a result is available.
In your case contents of the promise are all synchronous and therefore blocking.