Technology & Design

How to Use Async – Await in Angular 10

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!
Published by
Janki Thaker

Recent Posts

  • Automation

Overcoming Invoice Handling Challenges with AP Automation Solution

AI & RPA to automate invoices that can deliver…

3 days ago
  • Data & Analytics

10 Types of Power BI Dashboards for Every Industry!

Explore the different types of Power BI dashboards and…

5 days ago
  • RPA

Improve Business Operations with Power Portal and Power Pages

Benefit from Power Portal and Power Pages to help…

5 days ago
  • RPA

Why Organizations Need an RPA Strategy

Having an RPA strategy will help you avoid wasting…

5 days ago
  • Data & Analytics

Know Your Manufacturing Insights with Power BI Dashboard

Unlike other industries, manufacturing industries are always searching for…

5 days ago
  • AI/ML

Automating Patient Appointment Scheduling with AI and RPA

Patient Appointment Scheduling to automate healthcare workflows using RPA…

6 days ago