0

As javascript is synchronous, so we use callback promises and async await to make it asynchronous, but when we use async await it wait for the await statement to be completed before going to next statement, so technically this is synchronous then why it is written that async await is used to make javascript asynchronous. Please let me know if I am missing something

I checked many resouces but still its not clear to me

Shubham Singh
  • 199
  • 1
  • 3
  • 1
    You can think that a function marked with `async` keyword returns a promise. `await` part(s) of the function are the callback send to the promise constructor and `resolve` callback passed to `then`. Standardized behavior is [more complex](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-async-function-definitions), and the implementation details are engine-dependent. – Teemu Jan 03 '23 at 10:03
  • See also https://stackoverflow.com/questions/44512388/understanding-async-await-on-nodejs – NineBerry Jan 03 '23 at 10:06
  • `async`/`await` is just syntactic sugar that hides the "complexity" of `Promise`s – Andreas Jan 03 '23 at 10:09
  • 2
    Async/await doesn't "make javascript asynchronous" ... async/await is syntax sugar for promises to make asynch code *look* more synchronous. Now promises are just a way of dealing with asynchrony primarily (imo) to reduce the callback pyramid of doom. There is nothing special about promises, they use a callback paradigm `.then(callbackFn)` - so you're looking at async/await/promises all wrong - they don't make asynchrony, they "deal" with it – Jaromanda X Jan 03 '23 at 10:10
  • *"it wait for the await statement to be completed"*: `await` makes the `async` function **return**!! And then execution continues there. The `async` function will resume asynchronuosly some time after the current call stack is empty. – trincot Jan 03 '23 at 10:33

1 Answers1

2

How async await makes javascript asynschronous?

It doesn't. It is a tool to manage code that is already asyncronous.

As javascript is synchronous

It isn't. It runs a single main event loop and has rules for when stuff is handled outside of that loop.

when we use async await it wait for the await statement to be completed before going to next statement, so technically this is synchronous

The function containing the await statement goes to sleep until the promise (on the RHS of the await statement) resolves and the main event loop is free to pick the function up again.

Functions containing await statements must be marked with the async keyword which makes them return a promise.

The main event loop continues processing outside of that function where the calling function has access to the (unresolved) promise returned by the function marked as async.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335