JavaScript handles asynchronous operations like API calls, file reading, or timers using Promises and async/await. They help manage code that takes time to complete without blocking execution.
This blog explains promises and async/await with examples.
⭐ 1. What Is a Promise?
A Promise represents a value that may be available now, later, or never. It has three states:
- Pending – initial state
- Fulfilled – operation completed successfully
- Rejected – operation failed
⭐ 2. Creating a Promise
const myPromise = new Promise((resolve, reject) => {
let success = true;
if(success){
resolve("Operation successful!");
} else {
reject("Operation failed!");
}
});
myPromise
.then(result => console.log(result))
.catch(error => console.log(error));
Output:
Operation successful!
⭐ 3. Chaining Promises
let promise = new Promise((resolve) => {
resolve(5);
});
promise
.then(result => result * 2)
.then(result => result + 3)
.then(result => console.log(result)); // 13
⭐ 4. Async/Await
async functions return a promise. await waits for the promise to resolve.
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => resolve("Data fetched!"), 2000);
});
}
async function getData() {
let result = await fetchData();
console.log(result);
}
getData(); // waits 2 seconds → "Data fetched!"
⭐ 5. Error Handling with Async/Await
Use try and catch to handle errors in async functions.
async function fetchData() {
try {
let result = await Promise.reject("Failed to fetch data");
} catch(error) {
console.log(error); // Failed to fetch data
}
}
fetchData();
⭐ 6. Why Use Promises & Async/Await
- Avoid callback hell
- Handle asynchronous code cleanly
- Improve readability and maintainability
- Easier error handling
⭐ Conclusion
Promises and async/await are powerful tools for handling asynchronous operations in JavaScript. They make your code cleaner, readable, and easier to maintain while managing operations that take time to complete.
📌 Citations
🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/
🔗 External Javascript Documentation:
https://www.w3schools.com/js/