1

I am fairly new to Javascript and am writing this post off the top of my head, so please correct me if I am wrong with anything.

From what I know, asynchronous functions allow other processes to run in the background and then after the function is completed, it returns a promise that can either be resolved or rejected. Also since processes in async functions don’t run in a set order, we can use the await keyword to stop execution until a process is completed.

However, what baffles me is the difference in code execution between

function f1() {
  //do stuff
}

function f2() {
  //do stuff
}

function f3() {
  //do stuff
}

async function asyncFunc() {
  f1()
  f2()
  f3()
}

asyncFunc()

and this:

async function asyncf1() {
  //do stuff
}

async function asyncf2() {
  //do stuff
}

async function asyncf3() {
  //do stuff
}

function f() {
  asyncf1()
  asyncf2()
  asyncf3()
}

f()

????? (Apart from the obvious fact that the first example returns a promise)

Is calling async functions in a sync function the same thing as calling sync functions in an async function? Do they both result in the same output? If so, which one is preferred over the other?

5
  • well there are no awaits in your code... so it will be the same. What is preferred depends on the task at hand. Commented May 3, 2021 at 17:13
  • asynchronous functions allow other processes to run in the background and then after the function is completed, it returns a promise that can either be resolved or rejected. <-- Just because an operation is asynchronous doesn't mean that you'll have promises that can be resolved or rejected - - that's specifically available with the Promise API. AJAX operations are asynchronous but don't give you resolve/reject abilities natively. Commented May 3, 2021 at 17:15
  • Research suggestion - 1. what async functions actually do. 2. Multithreading in JavaScript. Specifically how it's an opt-in and most of the code still runs single-threaded. Commented May 3, 2021 at 17:16
  • The first one works, the second one doesn't. Whether to use async features is usually not your decision. Async functions have to be called from async functions (or async-aware sites that handle the resulting promises properly) Commented May 3, 2021 at 17:16
  • Possible duplicate of stackoverflow.com/questions/67354276/… Commented May 3, 2021 at 17:21

2 Answers 2

5

The key thing to understand is that async functions are syntactic sugar for using promises. Neither async functions nor promises make anything happen in the background. They let you wait for and react to things that already happen in the background (like a timer or an HTTP operation completing).

An async function is synchronous up until the first await or return. (That's so it can start whatever asynchronous process it then waits for.) At that point, it returns a promise that will be fulfilled or rejected depending on what happens to the promise being awaited and/or what you return.

await pauses the logic of the function until/unless the promise being awaited settles. (If you use await value where value isn't a thenable [a promise-like thing], you're effectively doing await Promise.resolve(value).)

You haven't shown any contents of the asyncFuncX functions, but unless they await something, they're fully synchronous.

You may find my answer from a couple of days ago useful as well.

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

6 Comments

I hadn't realized async functions are sync until the first await. My mental model had been that they are basically always dispatched into a task. TIL, thank you :)
@AKX - :-) A pleasure!
@ Jackbaklava (well, or anyone else) I go into Promises and async functions in a fair bit of detail in Chapters 8 and 9 of my recent book JavaScript: The New Toys. Links in my profile if you're interested.
@AKX if you have any familiarity with C++20 coroutines, the JavaScript implementation of async is the equivalent of using the suspend_never type for the initial_suspend() suspension point in the state machine, meaning async functions in JavaScript are eagerly started rather than lazily started. Conversely, generator functions in JavaScript are the equivalent of using the suspend_always type for the initial_suspend() suspension point since they are lazily started and only begin execution after calling generator.next().
Oh! So they are the same since I am not using any awaits. That explains everything. Thanks! :) @T.J.Crowder
|
4

Is calling async functions in a sync function the same thing as calling sync functions in an async function?

Not at all. async functions are arranged by the JavaScript execution environment to be executed in separate microtasks (after the first await, as explained in TJ Crowder's answer), out of the flow of the synchronous function. This means that async functions (can) continue running after the calling synchronous function has been returned out of.

If you run the below snippet, you can see the output being in, out, f1, f2, f3, even if the f function clearly seems to do in, f1, f2, f3, out.

(The example has an extra await noop() to truly make the async happen.)

async function noop() {}

async function asyncf1() {
  await noop();
  console.log('f1');
}

async function asyncf2() {
  await noop();
  console.log('f2');
}

async function asyncf3() {
  await noop();
  console.log('f3');
}

function f() {
  console.log('in');
  asyncf1();
  asyncf2();
  asyncf3();
  console.log('out');
}

f()

Conversely, calling a synchronous function in an async function works, but has the effect of blocking that task, and since JavaScript engines are single-threaded wrt JavaScript code, it blocks all other async tasks from executing "simultaneously" too.

Do they both result in the same output?

They don't. (Or, well, that's a philosophical question. If the functions don't return anything or do anything, then yes, the result could be perceived to be the same.)

2 Comments

@T.J.Crowder Clarified.
"If you run the below snippet, you can see the output being in, out, f1, f2, f3" only in this specific example. If there is no await in asyncf2, for example, then you'd get in -> f2 -> out -> f1 -> f3

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.