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 …


This content originally appeared on DEV Community and was authored by Dewald Els

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

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)
}


This content originally appeared on DEV Community and was authored by Dewald Els


Print Share Comment Cite Upload Translate Updates
APA

Dewald Els | Sciencx (2021-06-26T19:29:49+00:00) JavaScript: Async/Await Wrapper. Retrieved from https://www.scien.cx/2021/06/26/javascript-async-await-wrapper/

MLA
" » JavaScript: Async/Await Wrapper." Dewald Els | Sciencx - Saturday June 26, 2021, https://www.scien.cx/2021/06/26/javascript-async-await-wrapper/
HARVARD
Dewald Els | Sciencx Saturday June 26, 2021 » JavaScript: Async/Await Wrapper., viewed ,<https://www.scien.cx/2021/06/26/javascript-async-await-wrapper/>
VANCOUVER
Dewald Els | Sciencx - » JavaScript: Async/Await Wrapper. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/06/26/javascript-async-await-wrapper/
CHICAGO
" » JavaScript: Async/Await Wrapper." Dewald Els | Sciencx - Accessed . https://www.scien.cx/2021/06/26/javascript-async-await-wrapper/
IEEE
" » JavaScript: Async/Await Wrapper." Dewald Els | Sciencx [Online]. Available: https://www.scien.cx/2021/06/26/javascript-async-await-wrapper/. [Accessed: ]
rf:citation
» JavaScript: Async/Await Wrapper | Dewald Els | Sciencx | https://www.scien.cx/2021/06/26/javascript-async-await-wrapper/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.