Basics Of Angular And Its Versions - Part Six

Angular async/await

Before you start reading this article, please go through my previous articles for better understanding.

In this article, I am going to discuss more on async/await support. This async/await feature was officially announced in TypeScript 2.1. We can say this is one of the very important features of TypeScript 2.1 release.

So, what is async/await? It is nothing new; if you are a C# or Java developer, then you might have been using TPL (Task Parallel Library) in your code. Then definitely, you would have come across async/await keywords in C# or Java. So in TypeScript also, it is the same concept.

As we know, in TPL, async/await are the code markers. It marks the code positions from where the control should resume after a task completes. We cannot use await keyword without async, they are tightly coupled to each other. In Angular also, it works in the same way.

In my previous article, I explained, by default, Angular built-in HTTP services return Observable. To return the response as a Promise to a called method, at first, we have to convert the response to a Promise using toPromise() method.

Sample code snippet for Promise call.

  1. request(req: Request): Promise<any> {  
  2.         return this.http.request(req)  
  3.             .toPromise()  
  4.             .then((response: Response) => {  
  5.                 return response.text().length ? response.json() : null;  
  6.             })  
  7.             .catch((error: any) => this.handleError(error, req));  
  8.     } 

Now, let's rewrite the above code using async/await.

The sample code snippet using async/await will be something like this.

  1. async request(req: Request): Promise<any> {  
  2.      const resonse = await this.http.request(req).toPromise();  
  3.      return response.text().length ? response.json() : null;  
  4.  } 

If you observe, in the above code, I assigned the Promise call to a constant variable directly without Promise.then() and its call back method to it. This way, our code looks like sequential code even though the asynchronous operation is involved in it.

Notes

  • We cannot apply async/await to a class constructor. So, we can't change the class constructor from -

app.component.ts

  1. constructor(private testService: TestService, private _logger: Logger) {  
  2.     this.testService.getTestDetails(this.testId)  
  3.         .then(response => this.response = response);  

to

app.component.ts

  1. async constructor(private testService: TestService, private _logger: Logger) {  
  2.        this.response = await this.testService.getTestDetails(this.testId);  
  3.  

As a work around, we can make use of Angular life cycle hook events and can declare it as async.

The sample code is shown below.

app.component.ts

  1. constructor(private testService: TestService, private _logger: Logger) { }  
  2. async ngonInit() {  
  3.       this.response = await this.testService.getTestDetails(this.testId);  
  4. }   
  • async/await only works with Promises and it doesn't work with Observables.

Is it worth using async/await in our code?

My answer is Yes; it is a matter of personal choice. If we use async/await in our code, then we will get the following benefits,

  • The code will be concise and clean
  • It provides code that is much cleaner and more readable
  • It provides much nicer syntax for more complex scenarios.
  • Improves the performance
  • It returns the Promise implicitly
  • It gives the synchronous feel though it is an asynchronous code.

I would appreciate your valuable feedback. Happy reading.

<<Click here for the previous article


Similar Articles