JavaScript: Async/Await Wrapper
Reduce the number of try/catch blocks

I'm a TypeScript developer based in Oslo, Norway, coding professionally since 2010. I work across the full stack—frontend, backend, and databases—building web applications that are both functional and user-friendly.
Outside of work, I dive into game development with Godot. I'm currently exploring pixel art and using it to bring my hobby projects to life. I'm also passionate about software architecture and always looking for ways to improve the structure, clarity, and maintainability of my code.
Reusable function to run any Promise that returns an array of data and error.
Using Async/Await is great, but when working with multiple Promises it often clutters your code with multiple try/catch statements. I wrote this wrapper to easy encapsulate the try/catch and return an array with the data in the 1st index and the error in the second index.
Source code
Wrapper function
export const asyncWrapper = async (asyncFunction, params = null) => {
try {
const data = await asyncFunction(params)
return [data, null]
}
catch (error) {
return [ null, error ]
}
}
Implementation
// Use them all together! <3
const handleFetchAllClick = async () => {
// No gross try/catch everywhere
const [users, usersError] = await asyncWrapper(fetchUsersRequest)
const [todos, todosError] = await asyncWrapper(fetchTodosRequest)
const [user, userError] = await asyncWrapper(fetchUserByIdRequest, 1)
const [newUser, newUserError] = await asyncWrapper(createUsersRequest, mockUser)
}

![React: ContextAPI as State [ UPDATED ]](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1621595077407%2FHKHTcJx3d.png&w=3840&q=75)

