Understanding the async and await Keywords in Node.js: Why Asynchronous is Not Synchronous

preview_player
Показать описание
---

Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: Why we have to use keyword async and await to making it synchronus in node, when the keyword is literally async?

If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---

The Confusion Around async

What Does async Mean?

The async keyword is used to define a function that will always return a Promise. This is particularly useful for asynchronous programming within JavaScript. Here’s a breakdown of how it works:

Always Returns a Promise: Any function declared with the async keyword is designed to return a Promise. This becomes essential when dealing with asynchronous operations, enabling a more manageable coding approach.

Not Synchronous: Importantly, using async does not make any code synchronous. Instead, it utilizes a syntax that allows you to write code that appears to act synchronously.

How Does await Fit In?

The await keyword can only be used inside an async function. It pauses the execution of the function until the Promise is resolved or rejected. Although this resembles synchronous execution, it does not turn asynchronous code into synchronous code. Here’s how it impacts your code:

Suspension of Execution: When the execution hits await, it pauses the current function and allows other code to run in the meantime. This is where the asynchronous nature shines through.

Returning Control: After the awaited Promise resolves, control returns to the async function, which picks up exactly where it left off.

Example: Understanding the Flow

To clarify how async and await interact, consider the following code snippet:

[[See Video to Reveal this Text or Code Snippet]]

Breakdown of Output Order

If you run this code, you will observe the following output order:

before run()

in run() 1

after run()

in run() 2

When run() is called, it immediately logs "in run() 1" and then hits await, pausing execution.

Meanwhile, "after run()" gets logged before the delay finishes.

Finally, once the delay is done, "in run() 2" is printed.

Alternative with .then()

An equivalent operation can be achieved using .then(), as shown below:

[[See Video to Reveal this Text or Code Snippet]]

The output remains the same, demonstrating how promises can be handled through different syntax without changing the asynchronous nature of the code.

Conclusion

Remember, the beauty of async and await lies in their ability to simplify the complexity of asynchronous programming while respecting the asynchronous nature of JavaScript itself.
visit shbcf.ru