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, newer version of Ecmascript (ES) started supporting async-await feature. 

Async-Await 

As per 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}`); 

} 

Related Posts

How We Became a Top Mobile App Development Company in Columbus, Ohio

Sunflower Lab is a top mobile app development company in Columbus, Ohio for our integrity, exceptional solutions, and commitment to…

4 Ways Custom Software Development Can Help Startups

Investing in custom software development as a startup can be scary, but these 4 reason will likely convince you.

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!