JavaScript Async Reference
Asynchronous JavaScript with Promises, async/await, and fetch API
Promises Basics
const promise = new Promise((resolve, reject) => {
if (success) resolve(data); # success
else reject(error); # failure
});
promise
.then(data => console.log(data)) # handle success
.catch(err => console.error(err)); # handle error
Async/Await
async function fetchData() {
try {
const response = await fetch(url); # wait for promise
const data = await response.json(); # parse JSON
return data;
} catch (error) {
console.error(error); # handle error
}
}
Fetch API
# GET request
fetch("https://api.example.com/data")
.then(res => res.json())
.then(data => console.log(data));
# POST request
fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});
Promise Methods
Promise.all([promise1, promise2]) # wait for all
.then([res1, res2] => { });
Promise.race([promise1, promise2]) # first to finish
.then(result => { });
Promise.allSettled([p1, p2]) # all results
Promise.any([p1, p2]) # first success
Error Handling
# Promise chain
promise
.then(data => { })
.catch(err => { }) # catch errors
.finally(() => { }); # always runs
# Async/await
try {
await asyncFunction();
} catch (e) {
console.error(e);
}