Skip to content

Instantly share code, notes, and snippets.

@koolamusic
Last active October 8, 2022 14:21
Show Gist options
  • Save koolamusic/360c8e4cc8459f2c7511d672e71e4ad1 to your computer and use it in GitHub Desktop.
Save koolamusic/360c8e4cc8459f2c7511d672e71e4ad1 to your computer and use it in GitHub Desktop.
A Function to Handle executing other functions in an Asynchronous manner, using Async await, and tryCatch while handling errors declaratively
async function useAsyncHandler(callback) {
try {
const data = await callback
return [data, null]
} catch(error) {
console.error(error, "error log from async handler")
return [null, error]
}
}
const oneTodo = (id) => fetch(`https://jsonplaceholder.typicode.com/todos/${id}`)
.then(response => response.json())
.then(json => json)
async function getUserTodo(id){
const [data, error] = await useAsyncHandler(oneTodo(id));
// log the async response here
console.log(data, error)
}
// invoke the function
getUserTodo(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment