JavaScript Async/Await
Asynchronous JavaScript with Promises, async/await, and error handling.
Promises
# Creating a Promise
const promise = new Promise((resolve, reject) => {
if (success) resolve("Done!");
else reject("Error!");
});
# Using Promises
promise
.then(result => console.log(result))
.catch(error => console.error(error));
Async/Await
# Async function
async function fetchData() {
const response = await fetch(url);
const data = await response.json();
return data;
}
# With arrow function
const getData = async () => {
const data = await fetchData();
console.log(data);
};
Error Handling
# Try-catch with async
async function fetchData() {
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (error) {
console.error("Error:", error);
}
}
Promise.all
# Multiple promises
const promises = [
fetch(url1),
fetch(url2),
fetch(url3)
];
Promise.all(promises)
.then(responses => console.log(responses));
# With async/await
const results = await Promise.all(promises);