Technology & Design

How to Use Async – Await in Angular 2

Angular 2 came out with async-await feature, async function is called when callback functions are used which return promise. The async  will either return value and the promise return that value, or it will return an exception and the promise  get rejected.

Let’s see how to use async-await in Angular 2+

An async has await expression, await creates an understanding between async and promise and holds async function to wait till the promise is return. As soon as promise return the value the async function gets executed. By using await expression you overcome using addition setTimeout() function inside you promise.

Example:

src/bitcoinPrice.service.ts

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

import { Http } from ‘@angular/http’;

@Injectable()

export class BitcoinPriceService {

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

constructor(private http: Http) { }

async getPrice(currency: string): Promise {

const response = await this.http.get(this.bitcoinRateUrl ).toPromise();

return response.json().bpi[currency].rate;

}

}

 

src/bitcoinPrice.component.ts

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; constructor(private priceService: BitcoinPriceService ) { }

async ngOnInit() {

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

}

}

Above example shows how to use async function await expression in Angular 2+ project

Published by
Janki Thaker

Recent Posts

  • AI

Copilot Studio vs M365 Copilot: Which One Does Your Business Actually Need?

No vendor pitch here, just the plain difference, so…

2 weeks ago
  • Automation

Before You Automate: The 5-Process Audit Every Operations Director Should Run First

A process automation audit tells you which workflows are…

3 weeks ago
  • Automation

RPA Governance Without a Full IT Team: How Lean Operations Teams Keep Automations Running

Launching an automation is exciting. Keeping it running a…

3 weeks ago
  • Automation

3 Steps to Achieve Versioning and Drafts

Businesses are quickly shifting towards optimized processes. And the…

1 month ago
  • Automation

What Happens to Your RPA Program When Your ERP Upgrades? A Migration Playbook

Enterprise leaders usually celebrate when a major ERP modernization…

2 months ago
  • Automation

RPA Center of Excellence: Setup, Governance, and Scaling

Here's how to build the operating model that turns…

2 months ago