Reputation: 1
console.log('Start');
const myFunc = async () => {
for(let i=0; i<10000000000000; i++){}
console.log('After for loop');
}
myFunc();
console.log('end');
I want async behaviour using async/await. I want my function to pass the entire function to an event loop same as SetTimeout, SetInterval does so that my main thread can continue to do the rest unless that heavy functionality is running behind the scene.
Expected Output: Start, end, After for loop
Current Output: Start, AFter for loop, end
Upvotes: 0
Views: 102
Reputation: 29282
Your understanding of asynchronous javascript code is not correct.
Function passed to setTimeout
doesn't execute in the background - it executes on the main thread and while that function is executing, nothing else executes.
It's just that the callback function of setTimeout
is pushed in to the call stack after the timer has expired and the call stack is empty. This is why other code can execute before the callback function of setTimeout
executes.
Some functions provided by the browser such as HTTP requests happen in the background and once they are complete, Javascript will invoke our callback function and once that callback function starts executing, it blocks everything else from executing until that function is popped off the call stack.
Putting your code inside an async
function doesn't makes your code asynchronous; it will execute synchronously until the first await expression. (Promises do not make anything asynchronous. They are just a notification mechanism that notifies you of either successful completion or a failure of something that is already asynchronous.)
What you need is another thread that executes the long running code without blocking the main thread. You can do this using a web worker in the browser or worker thread in NodeJS.
Upvotes: 2