2

I have some code here...

async function test() {
    for(let i = 0; i < 10000; i++){
        console.log("test");
    }
}

console.log("a");
test();
console.log("b");

Now my understanding is that test() here should run asynchronously and if I would want to run a routine after it's completion I would use .then() after it.

I'm not doing that here though so surely it should just do it's thing in the background while everything else contiunes running? With that understanding I would expect some output like this:

a
b
test
test
..etc

However what I actually get is this...

a
test
test
...etc

b

Why does this happen? It seems that console.log("b") waits until test() completes but that's synchronous behaviour.

Apologies if something similar has been asked before but I couldn't find anything on this myself.

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Idiot
  • 23
  • 5
  • "It seems that console.log("b") waits until test() completes but that's synchronous behaviour." uh, no, that is the definition of async. Asynchronous: one action at a time while waiting for the completion of the previous to move to the next. – myself Jun 30 '22 at 02:07

5 Answers5

4

Setting something as async will wrap the return object into a Promise. Promises are used to deal with asynchronous behavior, but there's nothing inherently asynchronous about the content of the test function. If instead you were to wrap the contents into a setTimeout function, that would cause a delay which would mimic asynchronous behavior and match the outcome you were expecting.

async function test() {
  setTimeout(() => {
    for(let i = 0; i < 2; i++){
        console.log("test");
    }
  })
}

console.log("a");
test();
console.log("b")

If you're looking to set up background tasks that can lock up the browser's main thread, you should check out WebWorkers. They are a way to offload performance impacting tasks onto a separate thread.

GenericUser
  • 3,003
  • 1
  • 11
  • 17
  • So really Promises aren't much to do with asynchronous programming at all. They're just a way of giving a callback? – Idiot Aug 17 '19 at 11:17
  • Fundamentally they are intended for asynchronous programming. Using `async/await` on functions that do nothing asynchronous is usually a red flag. The returning `Promise` enables any other function a way to wait until it resolves, which is exactly the same as a callback. – GenericUser Aug 17 '19 at 11:22
2

Synchronous code inside an async function runs synchronously. The interpreter will only move on to the next line after the call of the async function (here, the console.log("b");) after all synchronous code has finished - for example, if it runs into an await.

Here, since there's no await or anything asynchronous at all going on in test, test runs to the end before the next line (that logs b) runs.

It's pretty similar to how the Promise constructor runs.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

From MDN:

An async function can contain an await expression, that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.

If you do not have an await expression you are never 'pausing' the coroutine and it will execute synchronously without letting other functions run.

supakeen
  • 2,876
  • 19
  • 19
0

an async function means that what is inside the function is expected to have some asynchronous calls. like if you had an Http call inside your test function.

and since nothing is asynchronous inside your function (you only have a normal loop) then your function will execute normally and sequentially until it finishes executing.

Hamza Mogni
  • 672
  • 1
  • 7
  • 21
0

async keyword don't mean that function wil run asynchronously. To run it asynchronously use setTimeout or Promise etc.

function test() {
  setTimeout(() => {
    for(let i = 0; i < 3; i++){
        console.log("test");
    }
  });
}

console.log("a");
test();
console.log("b");

Async keyword usually is used with Promises and await keyword to write async code in synchronous way (to use await keyword we need put code inside async function)

function test() {
  return new Promise( res => {
    for(let i = 0; i < 3; i++){
        console.log("test");
    }
    res();
  });
}

async function start() {
  console.log("a");
  await test();
  console.log("b");
}

start();
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345