Careeroza
Real World Example
Product Page Loader with Timeout and Retry
A product page on Amazon or Flipkart loads details, price and reviews from different services. Critical data is retried; a slow optional service should not block the page. This example uses typed generic helpers for timeout and retry.
Example
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
function withTimeout<T>(p: Promise<T>, ms: number, label: string): Promise<T> {
return Promise.race([p, sleep(ms).then((): never => { throw new Error(label + " timed out"); })]);
}
async function retry<T>(fn: () => Promise<T>, attempts: number): Promise<T> {
let lastError: unknown;
for (let i = 1; i <= attempts; i++) {
try { return await fn(); }
catch (e) { lastError = e; console.log(` attempt ${i} failed`); }
}
throw lastError;
}
let priceCalls = 0;
const getDetails = async () => { await sleep(10); return { id: 42, name: "Noise Earbuds" }; };
const getPrice = async () => { priceCalls++; if (priceCalls < 3) throw new Error("503"); return 1799; };
const getReviews = async () => { await sleep(200); return ["Great bass"]; };
async function loadProductPage() {
const [details, price, reviews] = await Promise.all([
getDetails(),
retry(getPrice, 3),
withTimeout(getReviews(), 50, "reviews").catch((): string[] => []),
]);
console.log(details.name, "Rs.", price, "| reviews:", reviews.length);
}
loadProductPage();Output
attempt 1 failed attempt 2 failed Noise Earbuds Rs. 1799 | reviews: 0