Member-only story

Using async-await feature in Angular

Balram Chavan
4 min readMar 4, 2018

Update: With newer version of Angular, we do not need to worry about promise returned from http(). We can still use async-await for other promise based logic though.

Check out my YouTube channel and subscribe to get more interesting videos.

Promises and callback functions are building blocks for writing asynchronous code in JavaScript.

In Angular application, we can use Rx.js to leverage power of Observables, Subject, BehaviorSubject etc for writing asynchronous code in elegant way.

With latest version of ECMA script draft, JavaScript started supporting “async-await” feature.

ECMAScript Latest Draft (ECMA-262)

If you are from C# background, you might be aware of “async-await” feature supported from C# 5 version.

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 passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.

In simple term, you shall get an opportunity to write an asynchronous code in synchronous fashion.

Example 1

Let’s consider a simple example. A function which returns a promise resolving after two seconds and returning value being passed as an argument.

Using promise, we can get the value using “then” callback function.

--

--

Balram Chavan
Balram Chavan

Written by Balram Chavan

Google Developer Expert Angular | Architect | Author | http://www.youtube.com/@angularcloud

Responses (36)

Write a response