How to handle promises without repeating try-catch?
// the magical function
async function promiseHandler(promise) {
try {
const data = await promise;
return [data, null]
} catch(error) {
console.error(error);
return [null, error]
}
}
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Resolve')
}, 1000)
})
const getDataFromAPI = async () => {
const [data, error] = await promiseHandler(promise)
// output: 'data' 'Resolve'
console.log('data', data)
// output: 'error' null
console.log('error', error)
}
getDataFromAPI()
June 17th, 2021
To avoid stuffing our functions with try-catch blocks when working with asynchronous code, we use a function (promiseHandler()
) which always returns an array containing the data for a resolved or the error for a rejected promise.