0
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

1
  • There is nothing asynchronous in myFunc. Everything is synchronous. Something that takes a long time isn’t automatically asynchronous. Commented Oct 8, 2021 at 4:53

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

If this is in node.js you'd similarly want to look at Worker Threads
@AlienWithPizza Thank you for the comment. I didn't notice that the question was tagged with nodejs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.