Last active
October 8, 2022 14:21
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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