JavaScript: Async/Await Wrapper
Dewald Els
Posted on June 26, 2021
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)
}
π πͺ π
π©
Dewald Els
Posted on June 26, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.