Back to Async / PromisesMedium
Exercise 8: Promise Chain with Error Recovery
Problem Statement
Function `withRecovery(promise, recoveryFn)` banao jo promise fail ho to recovery function call kare.
Example: withRecovery(fetchAPI(), () => getCachedData())
Sample Output:
await withRecovery(fetchAPI(), () => getCachedData()) // If fetchAPI fails, returns cached data
Solution
const withRecovery = async (promise, recoveryFn) => {
try { return await promise; }
catch (err) { return await recoveryFn(err); }
};Explanation
Overall Goal:
- Promise fail ho to recovery function se fallback.
Real world:
- API fallback: cache on failure.
- Error recovery: alternative data.