JavaScript: Async/Await Wrapper

dewaldels

Dewald Els

Posted on June 26, 2021

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 πŸ™
πŸ’– πŸ’ͺ πŸ™… 🚩
dewaldels
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.

Related