Async/Await in JavaScript
Before async/await, JavaScript used to write asynchronous code using callbacks and promises. You can take async/await as a syntactical sugar over the promises. The need to introduce async/await was because promise chaining was becoming hard to maintain. Async/await was introduced in 2017 to make asynchronous code look like synchronous code.
Async function
We write promise based code in a synchronous way. An async function always returns a promise.
Eg. async function greet() {
return "hello"
}
This is equivalent to,
function greet(){
return Promise.resolve("hello");
}
Await keyword
Await keyword pauses the execution of an async function until a promise resolves.
Eg. async function fetchData(){
let result = await fetch("example.api.com");
let data = await result.json()
console.log(data);
}
await keyword only works inside an async function. It makes the async code look synchronous and it also does not block the entire program, only the concerned function.
Error handling with async code
Here for error handling we use try...catch. The try block contains the code that might throw an error, if no error is thrown then catch block is skipped. If error occurs then catch block is executed. Finally block runs after the try and catch blocks are executed, it runs no matter what, whether there was an error or not.
Eg. try{
//code that can cause an error
} catch(error){
// how to handle that error
} finally {
//code that always runs
}
Like I mentioned earlier, that async/await is just a syntactic sugar over promises. This means that it does not replace promises but rather makes the promises easier to read, write and understand.
Difference between Promise and Async/Await
| Promise | Async/Await |
|---|---|
| A Promise represents the eventual completion or failure of an asynchronous task. | Async/Await is syntactic sugar for Promises. |
| Promises have 3 states - resolved, rejected and pending. | It does not have any states. It justreturns a promise either resolved or rejected. |
| Error handling is done using .then() and .catch() methods. | Error handling is done using .try() and .catch() methods, making it more similar to synchronous code. |
| Promise chains can become difficult to understand. | Makes it easier to read and understand the flow of the code as compared to promise chains. |
