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()
Copy

June 17th, 2021

# Simple way to handle promises

Add to bookmarks

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.

HomeBookmarks