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?