JavaScript Async/Await

JavaScript Async / Await are often used to simplify and make asynchronous programming more readable and maintainable.

Before Async/Await in javascript  first we see what is synchronous system and Asynchronous system.

What is a Synchronous System?

In a synchronous system, tasks are completed one after another.

Think of this as if you have just one hand to accomplish 10 tasks. So, you have to complete one task at a time.

Let’s see an Example:-

async await in javascript
  • Synchronous system, three images are in the same lane. One can’t overtake the other. The race is finished one by one. If image number 2 stops, the following image stops.

To test a synchronous system, write this code in JavaScript:

				
					console.log(" I ");

console.log(" eat ");

console.log(" Ice Cream ");
				
			
async await in javascript

In this example Code execute one by one line. 

What is an Asynchronous System?

In this system, tasks are completed independently.

Here, imagine that for 10 tasks, you have 10 hands. So, each hand can do each task independently and at the same time.

Let’s see an Example:-

async await in javascript
  • Asynchronous system, the three images are in different lanes. They’ll finish the race on their own pace. Nobody stops for anybody:

Write a code for asynchronous in javascript:

				
					console.log("I");

// This will be shown after 2 seconds

setTimeout(()=>{
  console.log("eat");
},2000)

console.log("Ice Cream")
				
			
async await in javascript

In this Example “eat ” message take time 2 sec extra  but see 3rd message print before 2nd because not wait for complition of 2nd message. 

Leave a Reply

Your email address will not be published. Required fields are marked *