JavaScript Async/Await

Posted by

  • JavaScript is synchronous in nature, meaning it follows an event loop mechanism. This event loop allows actions to be queued, but they are executed only when the loop becomes available, which typically happens after the code that queued the action has finished executing. This synchronous behavior ensures that actions are executed in a specific order and that one action is completed before the next one begins. Understanding the event loop is crucial for managing the execution flow and ensuring proper sequencing of tasks in JavaScript.
  • Async/Await is a powerful feature in JavaScript that extends promises, enabling developers to write asynchronous code in a more synchronous style. It provides a convenient and readable way to handle asynchronous tasks by utilizing familiar synchronous code structures. By using Async/Await, JavaScript code becomes more organized, easier to understand, and maintain, enhancing the overall programming experience.

Async

Async functions in JavaScript allow us to write promises-based code in a synchronous-like manner while ensuring non-blocking execution. They operate asynchronously through the event loop and always return a promise. If a value is not explicitly returned, JavaScript automatically wraps it in a resolved promise. This simplifies handling asynchronous operations and promotes cleaner code organization.

Example:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript async / await</h2>

<p id="demo"></p>

<script>
function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}

async function myFunction() {return "Hello";}

myFunction().then(
  function(value) {myDisplayer(value);},
  function(error) {myDisplayer(error);}
);</script>

</body>
</html>

OutPut:

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x