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

  • Podcast

AI in Business: Enhancing Human Productivity, Not Replacing It

In this episode of the The Lazy CEO Podcast,…

1 month ago
  • Podcast

Key to Digital Success: Insights from CEO of Sunflower Lab

Join us for an enlightening episode of The CEO…

1 month ago
  • AI/ML

5 Development Frameworks for Complex Multi-Agent AI System

Creating multi-agent workflows is the future of AI development,…

2 months ago
  • Podcast

Bridging Data Silos for Enhanced BI: Gaining The Technology Leadership Edge

How has sunflower lab's focus on integrating ai, data…

3 months ago
  • Automation

3 Steps to Achieve Versioning and Drafts

Businesses are quickly shifting towards optimized processes. And the…

4 months ago
  • Automation

6 Mistakes to Avoid in Power Automate

Developers often make mistakes when using Power Automate, which…

4 months ago