Async-await in Angular

Tram Ho

Definition of async-await

Creating a function with the async function statement will define an asynchronous function. When an async function is called, it will return a Promise . When the async function returns the value, the Promise will be resolved with the newly returned value. When the async function returns an exception, the Promise will be rejected.

The async function may include the await expression, which will suspend the execution of the async function and wait until the Promise is done to continue the async function. The await keyword is only valid within the async function. If you use it outside the async function body, you will get a SyntaxError.

Simply put, it is an opportunity for the code to be asynchronous in a synchronized fashion.

Example 1

Let’s start with a simple example. A function to return the Promise will resolve after 2 seconds, and return the value as the variable passed.

For promise , we can use the return value using the then() callback function then()

In this case, console.log() on line 5 will be printed before console.log() on line 3, which is the nature of promise .

Now let’s see how async-await works:

A few points to note

  • Line 1 – The function starts with async keyword, this keyword is required if await used in your function.
  • Line 2 – We do not call then() after the promise, instead we will add the await key in front. This keyword will not allow the next line of code to be executed, meaning console.log() in line 3 is only called when the promise in line 2 is resolved, just like when handling a synchronous function.
  • Because we use Typescript, we need to enter the return data type of the promise, as in the above example, <number> .

Example 2

In fact, ending in nested promises is very common (or callback hell), as in the above example we have two nested levels. But try to imagine with 7 or 8 nested floors, along with variables and exceptions, how scary it will look.

With async it will look like this:

A glance at it also makes it much simpler. Although it returns the same results, in terms of readability and maintainability, async-await is superior to the use of classic promises.

Use Http REST APIs

In Angular application, we can get data through Http or HttpClient service. By default, HttpClient methods like get() , put() , delete() , post() return Observable<T> . This result can be used via the subscribe method or the toPromise() operator from RxJs.

Get the HttpClient result using Observable

Many Angular devs use subcribe to get HTTP Rest data without even knowing how it differs from promise . The subscribe method will be taken from an Observable object. Once subscribe (registered), callback subscribe will be executed every time a new data generated by the Observer . Meanwhile, the promise callback then() will only be executed at most once. So unless you absolutely need to retrieve recurring data, don’t subscribe . Instead, use toPromise() . If you pay attention to the examples in Angular’s documentation, they are mostly used toPromise .

Get HTTPClient result using toPromise:

Rx.js provides a method called toPromise() , and we can use it to convert a Observable<T> into a promise. Once converted, the content within its then will be called whenever new data is available.

Get HTTPClient result using Async-Await

With Async-await syntax, we do not need to use both subscribe and toPromise . The code then looks very simple and intuitive. In the example below, the third line will be executed once the data is fetched from the “url”, Observable <T> is converted to promises, promises are resolved, and the data will be stored in the asyncResult variable.

Conditional programming:

A common case is that the program will need to retrieve data from a url, then consider the condition to fetch the next data. Using promises, the code will look like this:

Instead, if using async-await, the code would look like this:

In general, async-await provides a better way to handle asynchronous applications in Angular applications.


Chia sẻ bài viết ngay

Nguồn bài viết : Viblo