Promise?A Promise is an object in JavaScript that represents a value which may be available now, later, or never. Itβs used to handle asynchronous operations.
async and await
In JavaScript, async is used to declare an asynchronous function. It always returns a Promise.
The await keyword is used inside an async function to pause execution until a Promise is resolved, making asynchronous code easier to read.
async function getData() {
const response = await fetch("https://api.example.com/data");
const result = await response.json();
console.log(result);
}
getData();
Use Case: Ideal for handling API calls, timeouts, and non-blocking code.
const promise = new Promise((resolve, reject) => {
// async task here
});
resolve(): Called when the operation is successfulreject(): Called when the operation failsresolve)reject)
const fetchData = () => {
return new Promise((resolve, reject) => {
let success = true;
setTimeout(() => {
if (success) {
resolve("β
Data fetched successfully");
} else {
reject("β Failed to fetch data");
}
}, 1000);
});
};
fetchData()
.then(response => console.log(response))
.catch(error => console.log(error))
.finally(() => console.log("Operation completed"));
fetchData() returns a PromisesetTimeout simulates an async delayresolve() sends the success messagethen() handles the success outputcatch() handles the failurefinally() always runs, success or failthen() - Handles successful resolutioncatch() - Handles rejectionsfinally() - Runs after promise settles (either success or failure)Promise.all([]) - Waits for all promises to completePromise.race([]) - Returns the result of the fastest promisePromise.allSettled([]) - Returns results for all (whether fulfilled or rejected)Promise.any([]) - Returns the first fulfilled promise (ignores rejected)async and await?async - Declares a function returns a Promiseawait - Waits for the result of a Promise before continuing
async function getInfo() {
try {
let res = await fetch("https://jsonplaceholder.typicode.com/users/1");
let data = await res.json();
console.log(data);
} catch (err) {
console.error("Error fetching:", err);
}
}
Note: await can only be used inside async functions.
then/catch or async/await to handle resultscatch or try/catch to prevent crashesfinally ensures clean-up actions are performed