JavaScript
async/await Error Handling
Wrap async functions to uniformly catch exceptions.
By EZ4Code Team
asyncerrorwrapper
Code
async function to(promise) {
try {
const data = await promise;
return [null, data];
} catch (err) {
return [err, null];
}
}
// Usage
const [err, data] = await to(fetch("/api/user"));
if (err) return console.error(err);
console.log(data);Explanation
Mimics Go-style error handling, avoiding heavy try/catch nesting.
More JavaScript Snippets
Array Map Filter Reduce
Chain map, filter, reduce, find, some, and every on arrays.
Array Deduplication
Deduplicate an array using Set.
Deep Clone
Deep clone objects, supporting common data types.
Debounce Function
Wait a period of time after an event triggers before executing; reset the timer if triggered again during the wait.
Throttle Function
Limit a function to execute at most once within a time interval.
Promise.all Concurrency Control
A Promise executor with concurrency limit.