Asynchronous Programming 2- Async Await

In my previous blog, I have given a small introduction about Asynchronous Programming and told you that async and await will be my next blog topic.

Let's start.

I was using a number of functions which were returning the "promise" values and some "console.logs" statements. And both my statements' values were dependent on each other. So, I needed to wait for the second statement till the first statement completed. So I could get the fresh set of values to process those.  But because value was a "promise" type, both were executing independently. I fixed that situation with help of async and await.

The functionality of async and await :

async keyword lets typescript know that the function contains asynchronous instructions. But two async statements can depend on each other. So for maintaining that dependency, we can use await keyword to wait for the other statements.

An async function can contain an await expression. which pauses the execution of the other statements of async function and waits for the passed Promise value. Then the other statements of async function resume.

Explanation: In the below set of codes, there are two async functions. I am calling the “scheduleNotification()” function from “ngOnInit()” function. Look at the first statement of “ngOnInit()”. await keyword is used there. So unless we will get the promise result from that statement, the next lines of code will be in waiting state. Unless we will get permission we cannot schedule the notification.

export class HomePage implements OnInit{
 async ngOnInit(){
    await LocalNotifications.requestPermission();
    this.scheduleNotification();
  }
 async scheduleNotification(){
   await LocalNotifications.schedule({
    notifications:[
     {
       title: 'Basic Reminder',
       body: 'A pop up in instant',
       id:1,
       iconColor: '#0000ff'
      }
     ]
    });
  }
}

 

Hope it helps you to understand async and await. Thank you.

Reference: https://balramchavan.medium.com/using-async-await-feature-in-angular-587dd56fdc77

Add comment