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!

Kotlin Vs. Java - Which One To Choose?

Even though Java has more universal acceptance over Kotlin, there are a few instances where Kotlin scores over Java. Find how Kotlin is a better choice.

The newer, lightweight Kotlin, ideally suited for designing back-end systems for large sized companies, aimed to make existing Java models more powerful, resolve API related issues and improve the Android mobile development platform.

The release of Java 8 presented many new features that developers were eagerly waiting for. However, Java is not a modern language. Android supports a few Java 8 features. Moreover, Java has some well documented language issues, including endless try-catch blocks, a lack of extendibility and null pointer exception issue – Not to mention a lack of support for programming features

In spite of the fact that Java has begun to add some functional programming elements – lambda expressions and functional interfaces – at its core Java is still a procedural language. Java supports a verbose syntax, unlike many other advanced programming languages.

Advantages of Kotlin

So you may want to consider switching to one of the many modern programming languages designed to run on JVM. There is no shortage of programming languages which compile to Java bytecode. There are a few factors that make Kotlin stand out from the crowd:

Like many modern programming languages, Kotlin aims to bring you the best of both the worlds by combining certain elements and concepts from procedural and functional programming.

What Java has that Kotlin does not

  • Checked exceptions
  • Primitive types that are not classes
  • Static members
  • Non-private fields
  • Wildcard-types
  • Ternary-operator a ? b : c

What Kotlin has that Java does not

  • Lambda expressions + Inline functions = performant custom control structures
  • Extension functions
  • Null-safety
  • Smart casts
  • String templates
  • Properties
  • Primary constructors
  • First-class delegation
  • Type inference for variable and property types
  • Singletons
  • Declaration-site variance & Type projections
  • Range expressions
  • Operator overloading
  • Companion objects
  • Data classes
  • Separate interfaces for read-only and mutable collections
  • Co-routines


java lambda expressions

Java Lambda Expressions

Lambda expression is one of the new features of Java 8. It is mainly used to implement functional interfaces. This article covers 3 aspects:

  1. Traditional Approach (Anonymous Inner Class)
  2. New approach (Lambda Expression)
  3. Pros and cons of Lambda

1. Anonymous inner class

It is used for implementing interfaces or evoking the override methods of a class and/or an interface. it is declared and instanced at the same time. Just like creating an instance and defining local variables, it is created locally in the method, or at the class level. It does not have a name for itself so that’s why it is called an “Anonymous” inner class.

Image 1

In the above code, the snippet PerformCalulation is implemented when its interface is called. This is the anonymous inner class and its implementation overrides the calculate method.

Lambda Expression

It is used for implementing the functional interface.

What is a functional interface?

An Interface with only one abstract method is called a functional interface. A “@FunctionalInterfaceannotation is used to indicate a functional interface.

Image 2

In the above code, the snippet PerformCalculation interface is the functional interface. If you check Image 1 and Image 2, both will print 5. In image 2 we have used a Lambda Expression in lines 10 to 12.

Syntax of Lambda

(Parameter 1,Parameter 2)  ->  { method body }

Where:

  • Parameters 1 and 2 are argument lists which are passed on to the method.
  • The arrow mark is used to separate the argument list and the method body.
  • (the method body is the actual implementation of the method)

There are other syntaxes for lambdas and they depend upon the argument list as well as the method body:

 

Syntax Explanation
() -> true; // 0 parameters
a -> a.startsWith(“test”);   // 1 parameter
(String a) -> a.startsWith(“test”); // 1 parameter
(a, b) -> a.startsWith(“test”);      // 2 parameters
(String a, String b) -> a.startsWith(“test”); // 2 parameters
a, b -> a.startsWith(“test”); // DOES NOT COMPILE
a -> { a.startsWith(“test”); }; // DOES NOT COMPILE
a -> { return a.startsWith(“test”) }; // DOES NOT COMPILE

The sixth snippet is not compiled because if there is more than one argument it should be enclosed in a parentheses “().” Moreover, if you define an argument, it should be enclosed in parentheses too.

The seventh snippet is not compiled because it does not have a “return statement” – If you use braces “{}”  in the body than you should have a return statement in the body.

The eighth snippet will not compile because the line is missing a semicolon.

3. Pros and Cons of Lambda

Pros

  1. It has a simple, and easily readable syntax as compared to the anonymous inner class.
  2. It reduces the number of lines and boilerplate code in comparison to the anonymous inner class. In the code below, the highlighted blue syntax lines can be removed if we use Lambda.

3. When we compile the class containing the anonymous inner class, it will create one extra class file for the anonymous  class.

      Here the Lambda1$1.class file is created due to the anonymous class. However, if we  

      compile Lambda it will not create a class file.

Cons

We can only use it when we implement the functional interface.