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)
}
Top comments (7)
I would rather
export const asyncWrapper = async (fn, ...args) => {
Secondly, a general practice I have often seen is that
error
is always the first param, while the rest are the response from the function call.return [error, response]
;I initially used a closure and thought of using the rest operator there, but I didn't like the syntax. Although, it does afford the ability to create functions to use later.
I didn't see a need for this right now and decided to simplify it.
Hey! Thanks for the feedback! I do prefer the flexibility of the rest params, but for this example I didn't have a need for it. π It would be great to refine the function as the use cases start changing.
Seems several people have come up with the same idea! π npmjs.com/package/@jfdi/attempt
Nice! It's certainly not a new idea π
Merci beaucoup
π€£π€£π€£