The Javascript async await is used to make the promise easier to write and read, by allowing us to write code asynchronously that behaves more like the synchronous pattern. In Javascript async and await are introduced in ECMA script 2017, to achieve asynchronously in code.
Use of Javascript async await keyword.
The Javascript by default is synchronous, blocking, and single-threaded language. This means the Javascript engine can only process one code at a time in a single thread. When a thread is blocked we can’t execute other code is also blocked, this makes JS slow and inability to execute multiple operations.
Asynchronous make our code nonblocking, allowing us to execute multiple codes at the same time. In Javascript, we can achieve asynchronous using the following method.
- Callback
- Promise
In Javascript, we have an event loop, containing a four-part system(Stack, Heap, Event Queue, Event Loop), Event loop manages all operations in Javascript. Using the event loop Javascript executes asynchronous operations.
Advantages or features of async and await
- It make clarity in promise, easy to read and write.
- The async funciton implicitly returns a promise.
- Adding await on promise, if promise reject or error, we can handle it outside of async.
- We can use try and catch for error handling, uses same construct for handling error in both synchronouse and asynchronous.
Syntax of Javascript async and await
We can use async only or both async & await with promise. The syntax of Javascript async function with and without await keyword.
// async without await
async function functionName(parameters) {
//...statement
}
OR
// async with await
async function functionName(url) {
// statement ..
const resp = await fetch(url);.
return something;
};
The async function has the following parts.
Name | Description |
async | The async keyword, indicating the function is asynchronous. |
functionName | The name of a function. |
parameter | The parameter of function depends, it can one or many parameters. |
statement | The body of the function. |
await | Is optional, adding in front of an expression to wait for a promise to resolve and continue only then continue the execution of the function. |
Javascript async await example
Let demonstrate a few examples of Javascript async and await, as we learn that async implicitly returns a promise, and let demonstrate it in the example.
Javascript async function
An async function is a function declared with the async keyword, and the await keyword is permitted within them. The async keyword is placed before the function. Async and await make asynchronous code cleaner and behave a little more like synchronous code, which makes us easy to read and write.
- An async function is declared by the keyword async before the function keyword.
- Async function always return a promise
- Can add await keyword on a promise to wait to get the value it resolves to.
//Async function
async function hiAsync() {
return 'Hi from Async';
}
console.log(hiAsync());
//Promise
function promiseFun() {
return Promise.resolve("Hi from Promise");
}
console.log(promiseFun());
When we log the output of both functions, we can see that both functions return a promise in the image below.
![javascript async await](https://sp-ao.shortpixel.ai/client/to_webp,q_glossy,ret_img,w_338,h_143/https://edupala.com/wp-content/uploads/2021/12/javascript-async-await-example.png)
Both functions return a promise, we can see that async functions are easier to understand. Now how to access the return value of the async function, by using promise using then. Let continue with our first example.
async function hiAsync() {
return 'Hi from Async';
}
hiAsync().then((data) => alert(data));
We can access the return of Javascript async function, by using then on returning a promise. The then is nice but we can have a better option with async with await.
![Javascript async function return](https://sp-ao.shortpixel.ai/client/to_webp,q_glossy,ret_img,w_481,h_147/https://edupala.com/wp-content/uploads/2021/12/javascript-async-return.png)
Javascript await
The Javascript await operator is used to wait for a promise. By adding await in front of an expression make a promise to resolve or reject and only continue execution after the promise has been resolved.
The syntax of Javascript await the operator
We can’t use the async operators everywhere, it can be used either inside the async function or on their own with JavaScript modules. Using await keyword in the regular function will generate an error.
Here is the syntax of await operator.
async funtion functionName() {
....
const value = await promise;
}
Javascript convert Promise chaining to multiple Javascript await
In the async function, we can add multiple await keywords. Here is an example to convert the promise chain to Javascript await.
![Javascript await example](https://sp-ao.shortpixel.ai/client/to_webp,q_glossy,ret_img,w_585,h_206/https://edupala.com/wp-content/uploads/2021/12/javascript-await-example.png)
The async and await, really shine when we’re working with multiple promises. With async and await, we can assign each return statement from promise to a variable before passing this variable to the next function. This allows us, to chain multiple promises into a series of function calls inside a single function.
async function getEvenRange() {
const range = await numRange();
const evens = await findEven(range);
const sumOfEven = await getSumOfEvens(evens);
return sumOfEven;
}
// All Promise resolved and output 30
getEvenRange().then(data => {
console.log('Sum of even from 1 to 10 : ' + data);
});
function numRange() {
return 10;
}
function findEven(range) {
const evenArray = [];
for (let i = 0; i <= range; i++) {
if (i % 2 === 0)
evenArray.push(i)
}
return evenArray;
}
function getSumOfEvens(evens) {
let total = 0;
for (let i = 1; i < evens.length; i++) {
total = total + evens[i];
}
return total;
}
In the above example, we use async and await to execute the function sequentially, the output of one function is passed to the next function as an argument. The next function has to wait, as we applied to await until it previous is function is complete.
Convert Javascript promise to Async ans await
Let demonstrate a simple example to convert Javascript promise to async-await, we can’t see much difference on small code. We had seen in the previous example, Javascript async-await shines, when we have multiple chains of promise. The async and await have many advantages over-promise, one of them is easy to handle and debug error using try and catch.
The Javascript convert promises to async and await.
function getRates() {
return new Promise(resolve => {
const tax = 4;
setTimeout(() => resolve(tax), 5000);
})
}
//Using promise
getRates().then(res => {
const totalTax = 4000 * (res/100);
console.log('Tax calcuation inside promise : ' + totalTax);
})
// Using async and await
const calculateGST = async () => {
const taxValue = await getRates();
const totalTax = 4000 * (taxValue/100);
console.log('Tax calcuation inside async : ' + totalTax);
}
calculateGST();
Javascript Async await Error handling
Handling errors in Javascript async await is easy, we can handle errors in two ways.
- Using then on return of async function, which we had demonstrate earlier.
- The try/catch is best to handle error espcially when we are working with multple chaining of promises.
When our code had multiple chaining of promises, then If any of the promises that we await reject, we can easily handle the rejection error of promises.
Let demonstrate an example, we have used chains of function, in a real application, you can replace function with promise.
What we are doing, we have the function getStudent() to retrieve a particular student, in a real application, we have to use an API call to the server. Once we have a student record, we are calling another function to retrieve its id by passing a student record as an argument to that function.
At last, we are fetching courses taken by a particular student, by using some fake URL with his/her id. We use fake URLs so that we can invoke errors in the promise chains and catch the error.
async function getStudentCourses() {
try {
const student = await getStudent();
const id = await getID(student);
let courses = await fetch(`http://some-server-db-url${id}`);
return courses;
} catch (err) {
console.log(err.message);
}
}
getStudentCourses().then(data => {
console.log('Courses attend by student name: ' + data);
});
function getStudent() {
return { id: '23', name: 'Edupala' }
}
function getID(student) {
return student.id;
}
The above code will generate an error when it tries to access an inaccessible URL, so the error is caught in the try/catch statement. Here is an error we got by running the above code.
TypeError: Failed to fetch
Conclusion:
The async and await add clarity to the promise and make our code more behave like the synchronous pattern. Using async-await has lots of advantages, it makes code more clarity and we can easily use the try/catch construct to handle an error.
Related posts
- Javascript Map and Join function
- Differences between Javascript let vs var
- How to use Javascript detect browser type
- Functional Programming in JavaScript