async and await are used to handle asynchronous operations more cleanly & efficiently, avoiding the complexity of using raw Promises or callbacks.
async: Declares a function as asynchronous, which means it will always return a Promise. You can use await inside a async function.
await: Pauses the execution of an async function until a Promise is resolved or rejected.
- It allows you to write asynchronous code in a synchronous style, making it easier to read & write.
- Why was
async await created?
- To simplify working with Promises and to make asynchronous code easier to read & write.
- Asynchronous code can be written in a way that looks synchronous
- Avoids Callback Hell Javascript
- Before async/await, handling asynchronous operations required chaining promises using
.then() & .catch(), which could lead to complex code, especially in cases of multiple async operations Callback Hell Javascript
async function fetchData() {
let result = await someAsyncFunction(); // Waits for the Promise to resolve
console.log(result);
}
async function fetchData() {
try {
let result = await someAsyncFunction(); // Waits for the Promise to resolve
console.log(result);
} catch (err) {
console.error(err);
}
}