1. Promise
A Promise represents an asynchronous operation that may succeed (resolve
) or fail (reject
).
Example: placeOrder()
Function
Imagine ordering food online. The restaurant either:
✅ Resolves (success) → “Your pizza is on the way!”
❌ Rejects (failure) → “Sorry, item out of stock!”
sh
function placeOrder(item) {
return new Promise((resolve, reject) => {
const isAvailable = checkStock(item); // Assume this checks databaseif (isAvailable) {
resolve(`✅ Order placed: ${item} is on the way!`);
} else {
reject(`❌ Sorry, ${item} is out of stock!`);
}
});
}
Consuming the Promise (.then()
& .catch()
)
sh
placeOrder("Pizza")
.then((confirmation) => {
console.log(confirmation); // Success
})
.catch((error) => {
console.error(error); // Failure
});
Output:
-
If pizza is available →
"✅ Order placed: Pizza is on the way!"
-
If pizza is unavailable →
"❌ Sorry, Pizza is out of stock!"
2. Async/Await – A Cleaner Way
Instead of .then()
chains, we use async/await
for sequential-looking async code.
Example: trackOrder()
Function
sh
async function trackOrder(item) {
try {
const status = await placeOrder(item); // Waits for Promise to resolve
console.log(status);
return status;
} catch (error) {
console.error(“Order failed:”, error);
throw error; // Re-throw to let caller handle it
}
}// Usage:
trackOrder(“Burger”)
.then((status) => console.log(“Tracking:”, status))
.catch((err) => console.error(“Failed to track:”, err));
Key Improvements:
✔ No callback hell (cleaner than .then()
chains).
✔ try-catch
handles errors like synchronous code.
✔ throw
propagates errors to the caller.
3. Error Handling Best Practices
Do’s & Don’ts
Do ✅ | Don’t ❌ |
---|---|
Use try-catch with await |
Ignore errors silently |
throw new Error("msg") |
reject("msg") (in async functions) |
Log errors (console.error ) |
Swallow errors (no logging) |
Example: Proper Error Handling
sh
async function checkoutCart(items) {
try {
const order = await placeOrder(items);
const payment = await processPayment(); // Assume this returns a Promise
return { order, payment };
} catch (err) {
console.error("Checkout failed:", err);
throw new Error("Payment failed. Please retry."); // Custom error
}
}
4. Why This Example Works Better
-
Real-world scenario (food delivery → async operations).
-
Clear success/failure cases (in-stock vs. out-of-stock).
-
Extendable (can add
processPayment()
,deliverFood()
, etc.). -
Better error messages (user-friendly feedback).
5. Final Flow
-
placeOrder()
→ Returns aPromise
. -
trackOrder()
→ Usesasync/await
+try-catch
. -
Error handling → Logs + re-throws for caller.