JavaScript Async/Await & Promises Explained with Examples
Understanding JavaScript Promises & Async/Await
In this blog, we will learn how to handle asynchronous tasks in JavaScript. JavaScript is single-threaded, so long-running tasks like network requests can block the program. That’s why we use Promise, async/await, and try/catch/finally to manage them efficiently.
1. What is a Promise?
A Promise is an object that represents the future result of an asynchronous task.
const myPromise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("✅ Success!");
} else {
reject("❌ Failed!");
}
});
myPromise
.then(msg => console.log(msg))
.catch(err => console.log(err));
.then() → handles success, .catch() → handles errors.
2. Async/Await
Async/Await is a cleaner syntax to handle Promises.
async function fetchData() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
const data = await response.json();
console.log("User data:", data);
} catch (err) {
console.log("Error:", err);
} finally {
console.log("Fetch attempt finished!");
}
}
fetchData();
async function → makes the function asynchronous, await → waits for a Promise to resolve.
3. Try / Catch / Finally
- try: executes risky code
- catch: handles errors
- finally: always runs, for cleanup or hiding a spinner
4. Practical Example: Door Unlock
const unlockDoor = new Promise((resolve, reject) => {
const doorLocked = false;
setTimeout(() => {
if (!doorLocked) resolve("🚪 Door is unlocked!");
else reject("❌ Door is locked!");
}, 1500);
});
unlockDoor
.then(msg => console.log("Success:", msg))
.catch(err => console.log("Error:", err))
.finally(() => console.log("Attempt finished"));
5. Summary
- Promise → handles asynchronous tasks
- .then() / .catch() → handles success/error
- async/await → cleaner syntax
- try/catch/finally → error handling + cleanup
Tip: Any async task like fetch, API call, database query, or timeout returns a Promise. Using async/await makes the code more readable.
— End of Blog —
Comments
Post a Comment
Did this post spark any ideas? Drop your thoughts, questions, or insights — let's discuss!