1

I haven't used JavaScript for a long time, and now I'm trying to grasp the meaning of async/await keywords. I have found and read the tutorial on MDN (https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await) which left me with two questions.

  1. The tutorial says when I want to call an async function inside another async function, I have to use await. Why?

If I understand correctly async makes function runable into another thread. So every time I call a function marked with this keyword I make a new thread and get a Promise for this thread. If I can't do it inside async function does it means a thread in JavaScript can't spawn another thread? It seems like a browser can only run two threads: one main thread and one and only one extra thread. This makes all that fancy multithreading ability in JS a little bit thin.

  1. await can't be used outside of async function. Again: why?

I searched StackOverflow and I've found this question was answered elsewhere, but I want to know if something have changed in this matter for nowadays. I see this rather strange why I can't use await in the main thread. Why I can't wait for something? This makes me enclosing everything that must use some async functions into another async function every time. I know there may be an issue that, for example a code waiting for a long process loading something from the Web could make the rest of the webpage suspended for user interactions. But what about a callback for a button click? To use fetch() I have to make the callback async. But a callback can't be async, right?

3
  • 1
    JavaScript is a single-threaded language. Commented Jun 6, 2020 at 19:08
  • 1
    "If I understand correctly async makes function runable into another thread." no, it *only means that it will finish executing later. "This makes all that fancy multithreading ability in JS a little bit thin." there is very limited multithreading ability and async/await are not related to it. "for example a code waiting for a long process loading something from the Web could make the rest of the webpage suspended for user interactions." await doesn't block the thread. Quite the opposite it pauses the current execution to allow other tasks to run. Commented Jun 6, 2020 at 19:17
  • 1
    "The tutorial says when I want to call an async function inside another async function, I have to use await" you don't HAVE to. Only if you want to align your code in a way that lines make sense consequitively. You can fire an async function without awaiting it if you don't need the result. You can also mix it with promises but it's usually a bad idea only because await is syntactic sugar over promises and it's better to keep to one async abstraction. Commented Jun 6, 2020 at 19:19

3 Answers 3

5

Async / Await is just syntactic sugar. What does the async keyword do? It is an easy way to create a promise.

instead of:

const doSomething = () => new Promise((resolve,reject)=>{
  resolve("Hello")
})

We can do:

const doSomething = async ()=> "Hello"

A async function is a promise, what you return is the resolve if you throw you reject.

Await is a different way to do .then(), so you don't need to nest your code. See this gif for the evolution of asynchronous handling in javascript.

enter image description here

Image form: phpnews.io

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

Comments

2

The tutorial says when I want to call an async function inside another async function, I have to use await.

You don't have to, it just makes little sense not to.

If you use await then the function will go to sleep until the promise resolves and you have the resolved value.

If you don't use await then you get the promise itself. Sometimes this is useful (e.g. if you want to collect several promises to pass to const results = await Promise.all(array_of_promises)) but most of the time this would be mixing await syntax with then syntax which quickly becomes a confusing mess.

If I understand correctly async makes function runable into another thread.

No. It makes the function return a promise and allows it to go to sleep while it awaits another promise.

There is no thread spawning (look at Workers for as close as you get to threads in JS).

await can't be used outside of async function. Again: why?

Note the exception: It can in environments that implement top level await.

You can't get a value from a promise before a promise resolves. So if you wanted to wait for it then you have two choices:

  • Stop everything
  • Stop something

Stopping everything is a terrible idea. It stops, for example, event handlers from doing unrelated things while you wait (again for example) for a database access.

So the something you stop is the async function. Since the function has to return something, using async makes that function return a Promise.

Outside of the async function, code can get the Promise and keep running as normal. Just like traditional Promise syntax.

But what about a callback for a button click? To use fetch() I have to make the callback async. But a callback can't be async, right?

Of course it can. It is just a function.

The only things that you can't make async are functions where the calling function needs the return value to be something other than a Promise.

The return value of a callback function almost never matters. Certainly not in the case of an event handler (in legacy code it matters if an event handler returns true or false, but we've have an Event object passed as the first argument to event handlers since the 1990s).

Comments

0

You mentioned:

The tutorial says when I want to call an async function inside another async function, I have to use await.

The documentation doesn't say about using an async function inside another async function.

JavaScript is a single-threaded language. It was never multithread. That is the reason we have Promises in javascript.

async/await is just he syntactic sugar as people say it to write Promise in a cleaner way.

await can't be used outside of async function. Again: why?

That is how async is designed. You cannot use await without using async. Just like you cannot use .then without using Promise.

3 Comments

Wait a minute...if JS is single-threaded only language, then what 'async/await' are for? Does 'asynchronous code' =/= 'multithreading'? If that so, how it can run code in parallel?
No anything that is asynchronous will be put into something that's called event queue and the event loop will be looping over it to see if it is ready for execution. Once it is then it will put them into the call stack for execution. The easiest way to understand this is by the simple onclick event. it happens only when we click. that is because of this asyncronous approch
So by doing this the rest codes won't get blocked. So it can keep doing what its doing. that's why node js is faster than most of the tech out there

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.