Problem Statement
Modern JavaScript is heavily async/await based. Implement a debounce that works seamlessly with Promises, allowing callers to await the debounced result.
Requirements
Implement an asyncDebounce(func, wait) function that:
- Returns a function that returns a Promise
- All callers within the wait period receive the same Promise
- The Promise resolves/rejects based on the actual function execution
- Supports cancel() which rejects pending promises
Example Usage
const searchAPI = async (query) => {
const response = await fetch(`/api/search?q=${query}`);
return response.json();
};
const debouncedSearch = asyncDebounce(searchAPI, 300);
// Multiple components can await the same search
async function SearchComponent() {
try {
const results = await debouncedSearch("react");
console.log("Component 1:", results);
} catch (e) {
console.log("Search cancelled or failed");
}
}
async function SearchSuggestions() {
try {
const results = await debouncedSearch("react"); // Same promise!
console.log("Component 2:", results);
} catch (e) {
console.log("Search cancelled or failed");
}
}
// Both components get the same results from one API callEdge Cases
- What if the async function throws?
- How do you handle cancel with pending promises?
- What about concurrent debounced calls to different functions?
Follow-up Questions
- How would you add request deduplication on top of this?
- Should cancelled promises reject or stay pending forever?