I am trying to understand the async-await syntax deeply. So I write some code to illustrate what I know about async-await. Here is my code:
doSomething();
doFirst();
async function doSomething() {
const result = await stackUp();
console.log(result);
}
function doFirst() {
console.log('first');
}
function stackUp() {
let counter = 0;
while (counter < 4000000000) {
counter++;
}
return counter;
}
I called doSomething() then doFirst(). The while loop is used to delay the process. The console logs out first then 4000000000 as intended. To what I understand so far, first should be consoled out immediately then wait for stackUp() to finish counting and 4000000000 will be next. But the problem is first isn't consoled out immediately. I still have to wait for stackUp() to finish then both will be logged out. If I use setTimeout() to delay, everything works fine. Is this happens because while loop runs in JavaScript runtime and blocked the code?
awaitpauses the function that contains it and tells a promise to resume it – it doesn’t start threads or anything. If you don’t involve a promise at all, like in this case, it does nothing.--experimental-workerandworker_threads.Worker. If browser, using a web worker. (You can also just yield to the event loop occasionally while doing work, but that’s usually not a good idea.)