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.
- request(req: Request): Promise<any> {
- return this.http.request(req)
- .toPromise()
- .then((response: Response) => {
- return response.text().length ? response.json() : null;
- })
- .catch((error: any) => this.handleError(error, req));
- }
Now, let's rewrite the above code using async/await.
The sample code snippet using async/await will be something like this.
- async request(req: Request): Promise<any> {
- const resonse = await this.http.request(req).toPromise();
- return response.text().length ? response.json() : null;
- }
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
- constructor(private testService: TestService, private _logger: Logger) {
- this.testService.getTestDetails(this.testId)
- .then(response => this.response = response);
- }
to
app.component.ts
- async constructor(private testService: TestService, private _logger: Logger) {
- this.response = await this.testService.getTestDetails(this.testId);
- }
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
- constructor(private testService: TestService, private _logger: Logger) { }
- async ngonInit() {
- this.response = await this.testService.getTestDetails(this.testId);
- }
- 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