Does really async/await useful ?

Selvaganesh
3 min readMar 21, 2018

--

Async await is new way to write asynchronous code that skips use of callback and promise.It allows to flow data without blocking main thread and also more readable,you can think already to avoid callback promise was introduced now again to overcome that async/await born

Before starting first we will see how syntax looks like

async/await syntax

Have you seen within two lines of code we able to return a response back, Yay! that is beauty of async/await!

Here i have used a keyword “fetch” it is new API interface for fetching network calls,similar to XMLHttpRequest but fetch provides promise way feature will be a quite easier.

fetch keyword syntax

Normally fetch takes one mandatory argument,(i.e apiendpoint) the path where your api call want to perform and it returns a promise that resolves to the response.

methods available in fetch

Fetch also provides all network related function calls.

Now async function returns a promise, so you can simply call .then and .catch of the return value.

returning response

As you can see in the below example way more readable when written with async/await.

example using fetch keyword

To use fetch in node js try npm module node-fetch, in browser by default it will be available in window object.

One more important feature it is possible to handle synchronous and asynchronous errors using traditional try catch blocks

Use traditional try/catch block

If you feel not familiar in using “fetch” use “axios” or “request” to do the same.

But remember fetch and axios modules are advisable to use since by default it is promise based HTTP client whereas request module need an additional promise return object

Using request npm module

Now async functions landed across all latest browsers, use them on every promise-returning function! Not only do they make your code tidier, but it makes sure that function will always return a promise.

--

--