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

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/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.