This JavaScript tutorial help to understand async-await concept.The asynchronous function help to run tasks or process parallel without any callback hell.
The JavaScript is single thread programming language.That means only one operation can be carried out at a time.
Sometime single task can be take more time to execute and another task wait for execution.
Above scenario might be generate the callback hell issue, callback hell condition happening into js application due to poor coding and nested callback method.You can avid callback hell problem using async-await.
The EcmaScript2017 introduced Async and Await statements, which helps to run a promise-based method, without blocking of main thread application.
Basics Of Async-Await
- You can use with nodejs as well
-
async
is used for function declaration. -
await
is used for promise handling. -
async
function always returns a promise.
Whats is async
The Async statement is to create an async method in JavaScript.The function async is always return a promise.That promise is rejected in the case of uncaught exceptions, otherwise resolved to the return value of the async function.
Whats Await in JavaScript
The await is a statement and used to wait for a promise to resolve or reject. It can only be used inside an Async function.
Simple Example of Async and Await
The below example is the simple example and usage of async and await –
function hello() { return new Promise((resolve,reject) => { setTimeout(() => { resolve('I am adam.'); }, 2000); }); } async function async_msg() { try { let msg = await hello(); console.log(msg); } catch(e) { console.log('Error!', e); } } async_msg();
Output:
I am adam.
The Async method return value
The return value of the async method is always a promise. Have a look below example –
async function testAsync() { return 'Hello Adam!.'; } const promise_object = testAsync(); console.log(promise_object );
If you run the above code, then you will get the object Promise as a return value. You can access hello message using then() method like below –
promise_object .then(msg => console.log(msg)); // Hello Adam!.
How To Define Async Method Using Expression
We can also define an async method as a function Expression –
function hello() { return new Promise((resolve,reject) => { setTimeout(() => { resolve('I am adam.'); }, 2000); }); } async function async_msg() { console.log('I am in async method') const msg = await hello(); console.log('Message:', msg); } async_msg();
How To Run Multiple Method Async in Js
You can access all promises in JavaScript as well. We can catch all promises using Promise.all
method, This method helps to run method parallel.
The Promise.all() returns an array with the resolved values once all the passed-in promises have been resolved.
function hello() { return new Promise((resolve,reject) => { setTimeout(() => { resolve('Hello!I am'); }, 2000); }); } function user_name() { return new Promise((resolve,reject) => { setTimeout(() => { resolve('adam'); }, 2000); }); } function user_city() { return new Promise((resolve,reject) => { setTimeout(() => { resolve('from denver.'); }, 1000); }); } async function async_msg() { console.log('I am in async method') const [hello_msg, name, city] = await Promise.all([hello(), user_name(), user_city()]); console.log(`${ hello_msg } ${ name } ${ city }`); } async_msg(); </script>
Above code result would be –
I am in async method Hello!I am adam from denver.
How To Handle Error in Async-await
We can also add a try and catch block to handle errors and catch exceptions.
function hello(name) { return new Promise((resolve,reject) => { setTimeout(() => { resolve('Hello!I am '+ name +'.' ); }, 2000); }); } async function async_msg(name) { try { console.log('in async method'); const msg = await hello(name); console.log(msg); } catch(err) { console.log('Error:', err.message); } } async_msg('Adam');
Rest API With Async-Await
Nowadays, We are working much more with rest APIs, we are totally dependent upon the rest API to get and update data.
The JavaScript provides a fetch API to get data from the rest API, The fetch web APIs is a promise-based method.It returns a Promise that resolves the Response to that request.
async function fetchEmployees() { const resp = await fetch('https://dummy.restapiexample.com/api/v1/employees'); let results = await resp.json(); emps_name = results.map(name => results.employee_name); console.log(emps_name); } fetchEmployees();
The above code will return the employee’s name array.
await is only valid in async function
Sometimes, Async function throws error and says “await is only valid in async function”. The issue is that, You can only use await inside an async function. The await makes a function asynchronous, so it must be declared as such.