Angular 10 Async Await Example

Angular 10 was released to improve the quality, tool, and ecosystem of the platform for mobile apps (iOS and Android) and web apps. If we want to write asynchronous code in Javascript, promises and callback functions are the building blocks. In Angular, we use Rxjs to leverage power of Observables, Subjects, BehaviourSubject for writing asynchronous code. After javascript evolved in Ecmascript, a newer version of Ecmascript (ES) started supporting the async-await feature. 

Async-Await

According to MDN:

When an async function is called, it returns a Promise. When the async function returns a value, the Promise will be resolved with the returned value. When the async function throws an exception or some value, the Promise will be rejected with the thrown value. 

An async function can contain an await expression, that pauses the execution of the async function and waits for the past Promise’s resolution, and then resumes the async function’s execution and returns the resolved value.

Example 1

Consuming Http Rest API using async-await 

import { HttpClient } from ‘@angular/common/http’; 

import { Injectable } from ‘@angular/core’; 

@Injectable() 

export class BitcoinPriceService { 

private bitcoinRateUrl = ‘http://api.coindesk.com/v1/bpi/currentprice.json‘; 

constructor(private readonly httpClientHttpClient) { } 

async getPrice(currency: string): Promise<any> { 

return this.httpClient.get<any>(this.bitcoinRateUrl).toPromise(); 

} 

} 

 

import { Component, OnInit } from ‘@angular/core’; 

import { BitcoinPriceService } from ‘./bitcoinPrice.service’; 

@Component({ 

selector: ‘my-app’, 

template: ‘1 BTC = {{ price | currency:”USD” }}’ 

}) 

export class BitcoinPriceComponent implements OnInit { 

price: number; 

currency: string; 

constructor(private readonly priceServiceBitcoinPriceService ) { } 

async ngOnInit() { 

this.price = await this.priceService.getPrice(this.currency); 

} 

} 

Example 2

How Async-Await reduces the burden of callback chains and makes the code cleaner.  

Code Without async-await 

addWithPromise() {,  

       this.resolveAfter2Seconds(20).then(data1 => { 

              let result1 = <number>data1; 

              this.resolveAfter2Seconds(30).then(data2 => { 

                    let result2 = <number>data2; 

                    this.additionPromiseResult = result1 + result2; 

                    console.log(`promise result: ${this.additionPromiseResult}`); 

             }); 

     }); 

} 

 

 

 

Code with async await 

async addWithAsync() {,  

       const result1 = <number>await this.resolveAfter2Seconds(20); 

       const result2 = <number>await this.resolveAfter2Seconds(30); 

       this.additionAsyncResult = result1 + result2; 

       console.log(`async result: ${this.additionAsyncResult}`); 

} 

Coding with Angular 10 Async - Await

And just like that, you’re on your way to programming Async – Await In Angular 10! We hope these Angular 10 Async Await examples have helped you better understand the framework and language. Come back again soon for another guide on how to program your next project. Happy coding!

Related Posts

Digital Transformation Strategy for 2022: First Steps, Benefits, Technology

Digital transformation is a movement to modify existing business processes to meet the needs to today’s digital age.

Android vs iOS Which Platform to Build Your App for?

Android vs iOS Which Platform to Build Your App for? Discover pros and cons, demographic information, pricing, development timeline, and…

#1 Mobile Application Development Company in New Jersey

Sunflower Lab is a mobile app development company in New Jersey. This is how we set ourselves apart from the competition.

Get a FREE estimate for your project today.

Our team of experts will review your project and give you a quote at no cost.

Get a quote on your project!