Using async-await feature in Angular
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.
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 aPromise
. When theasync
function returns a value, thePromise
will be resolved with the returned value. When theasync
function throws an exception or some value, thePromise
will be rejected with the thrown value.An
async
function can contain anawait
expression, that pauses the execution of the async function and waits for the passedPromise
's resolution, and then resumes theasync
function's execution and returns the resolved value.
In simple term, you shall get an opportunity to write an asynchronous code in synchronous fashion.