3

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?

4
  • 3
    Yep, that’s why it happens. await pauses 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. Commented Aug 24, 2019 at 17:51
  • Is there a way for me to run the while loop asynchronously? Commented Aug 25, 2019 at 15:40
  • 1
    If Node.js, in a separate process using cluster or child_process, or using --experimental-worker and worker_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.) Commented Aug 25, 2019 at 17:10
  • Oh I understand. Thank you so much Commented Aug 26, 2019 at 9:17

2 Answers 2

1

Async await doesn't actually let you multithread your JS code. It still all runs synchronously by default, but anything awaited will be attached to the callback of the promise it awaits. If you want to run JS truly multithreaded, you would have to place your code running outside the main thread in a webworker and await a promise based on communications with the webworker.

TLDR; You can't multithread JS directly

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

Comments

0

Async/Await behaves like synchronous code execution that why its console both the output at the same time.

Async method execution goes to the callback queue.The callback queue works with the event loop in executing the callback functions.

Non-callback functions (doFirst) will go to main call stack.

After the code execution of main call stack , it will execute the callback queue with the help of Event loop, if Callback queue has codes to execute then it pops the message from it to the Main Stack for the execution.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.