ES6 offers a new way of writing more readable and scalable code to handle promises. In this article, we are going to discuss async
and await
in Javascript.
Before jumping on the topic, Let's discuss Asynchronous and Synchronous programming first.
Asynchronous and Synchronous
Javascript by default provides a single-threaded or synchronous programming environment which means it performs one operation at a time. When one operation is completed, only then another operation will start. This makes other operations wait or block hence called Blocking
.
In Asynchronous programming, one operation does not block the other operations. In fact, they execute in parallel. The Asynchronous operation executes in the background, making space for other operations to take place.
Asynchronous functions are important in Javascript programming. With the help of asynchronous functions, you can take care of other things without blocking the main program. For example, Fetching data from an API. Fetching data sometimes takes time and we should not block the main thread until data loads completely. We can write asynchronous operations to fetch data without blocking the main thread.
Async
and Await
in Javascript are one way to work with asynchronous functions/code.
Async
In Javascript, we can create async functions using the async
keyword. These functions always return a promise.
async function fnName(){
console.log('Hi! I am an async function');
}
or
const fnName = async ()=> {};
since the async function returns a promise, you can use the method chaining like below
fnName().then((result: any)=> {
console.log(result);
});
Can I use the return keyword in async functions?
Yes. When you use the return
statement to return a value from an async function, that function will return a resolved promise. value of the promise will be the value promise returned.
Await
The Await keyword in Javascript is used with the async function to wait for the operation to complete. You can use the await
keyword only in the async functions.
async ()=> {
let value = await promise;
};
await
keyword suspends the function execution until the promise settles/resolves.
Benefits of Async functions
- Code becomes more readable, maintainable, and scalable.
- Simple error handling through the
Try...Catch
block.
I hope this article helped you to understand the usage of async
and await
keywords. If you have any suggestions, please let me know in the comments section.