"async and await make promises easier to write". They are built on top of Promises, but they allow you to write asynchronous code that looks and behaves like synchronous code.
The keyword async before a function makes the function
return a Promise, even if it returns a non-promise value.
async function myFunction() {
return "Hello";
}
// Is equivalent to:
function myFunction() {
return Promise.resolve("Hello");
}
The keyword await can only be used inside
an async function. It makes JavaScript wait until the promise settles and
returns its result.
async function getDisplay() {
let myPromise = new Promise(function(resolve) {
setTimeout(function() {resolve("I love JS!!");}, 3000);
});
document.getElementById("demo").innerHTML = await myPromise;
}
getDisplay();
Instead of using .catch(), you can use the standard JavaScript
try...catch block to handle errors in an async function.
async function fetchData() {
try {
let response = await fetch('url');
let data = await response.json();
console.log(data);
} catch (err) {
console.log("Something went wrong:", err);
}
}
.then() chains and keeps everything in a flat, linear
structure.
async makes a function return a Promiseawait pauses the execution until the Promise settlesawait only works inside async functionstry...catch for professional-grade error management
Promise.all()await in loops if the tasks can run simultaneously