DEV Community

Cover image for JavaScript: Async/Await Wrapper
Dewald Els
Dewald Els

Posted on • Edited on

JavaScript: Async/Await Wrapper

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

GitHub Respository

Wrapper function

export const asyncWrapper = async (asyncFunction, params = null) => {
    try {
        const data = await asyncFunction(params)
        return [data, null]
    }
    catch (error) {
        return [ null, error ]
    }
}
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

🤓 Thanks for reading 🙏

Top comments (7)

Collapse
 
vishalraj82 profile image
Vishal Raj

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];

Collapse
 
dewaldels profile image
Dewald Els • Edited

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.

const fetchUsers = asyncWrapper(fetchUsersRequest);

// some other code
const [ users, error ] = await fetchUsers();
Enter fullscreen mode Exit fullscreen mode

I didn't see a need for this right now and decided to simplify it.

Collapse
 
dewaldels profile image
Dewald Els

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.

Collapse
 
jonsilver profile image
Jon Silver

Seems several people have come up with the same idea! 😁 npmjs.com/package/@jfdi/attempt

Collapse
 
dewaldels profile image
Dewald Els

Nice! It's certainly not a new idea 😆

Collapse
 
doctarhyf profile image
Docta Rhyf

Merci beaucoup

Collapse
 
doctarhyf profile image
Docta Rhyf

🤣🤣🤣