DEV Community

Discussion on: Error Handling in JavaScript (Golang Style)

Collapse
 
douglascalora profile image
DouglasCalora • Edited
import { Loading, Notify } from 'quasar'

/**
 * @param {Promise} promise
 * @param {object} config={notifySuccess, notifyError, useLoading}
 * @example promiseHandle(new Promise(), { notifyError: { message: 'Erro' }, notifySuccess: { message: 'Sucesso' } })
 */
export default async function (promise, config = {}) {
  const {
    notifySuccess = {},
    notifyError = {},
    useLoading = false,
    onLoading
  } = config

  onLoading && onLoading(true)
  useLoading && Loading.show()

  const primiseToBeExec = typeof promise === 'function' ? promise() : promise
  const hasNotify = notify => Object.keys(notify).length

  try {
    const data = await (Array.isArray(promise) ? Promise.all(promise) : primiseToBeExec)
    hasNotify(notifySuccess) && Notify.create({ type: 'success', ...notifySuccess })
    return { data, error: null }
  } catch (error) {
    hasNotify(notifyError) && Notify.create({ type: 'error', ...notifyError })
    return { data: null, error }
  } finally {
    onLoading && onLoading(false)
    Loading.hide()
  }
}
Enter fullscreen mode Exit fullscreen mode

I added a callback onLoading so I can do somenthing while function is running.

const { data, error } = await promiseHandler(callbackFn, { onLoading: value => console.log('is loading?', value) })

Collapse
 
bibekkakati profile image
Bibek

👨🏼‍💻