Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Nicer try/catch for async await.
/* Helper buddy for removing async/await try/catch litter 🗑 */
function O_o(promise) {
return promise.then(data => {
if (data instanceof Error) return [data]
return [null, data]
}).catch(err => [err])
}
/* Look ma, no try/catch */
async function usageExample(params) {
const [ err, data ] = await O_o(myPromise(params))
if (err) {
// handle or throw err
throw new Error(err)
}
// Do stuff with data
return data
}
/* Normal promise */
function myPromise(params) {
return new Promise((resolve, reject) => {
callbacker(params, (error, data) => {
if (error) return reject(error)
return resolve(data)
})
})
}
/* Normal callback */
function callbacker(params, cb) {
return cb(null, params)
}
// Run the thing
const params = {lol: 'true'}
usageExample(params).then((result) => {
console.log('result', result)
}).catch((err) => {
console.log('error', err)
})
@gunar

This comment has been minimized.

@kalisjoshua

This comment has been minimized.

Copy link

commented Apr 23, 2019

For your consideration:

const doOrDoNot = (result) =>
  result instanceof Error
    ? [result]
    : [null, result]

const thereIsNoTry = (promise) =>
  promise
    .then(resolve, resolve)
@DavidWells

This comment has been minimized.

Copy link
Owner Author

commented Apr 24, 2019

Updated based on @gunar's library https://gist.github.com/DavidWells/56089265ab613a1f29eabca9fc68a3c6

I think one of the biggest cons of the above code is it could swallow syntax errors and other bits that would be very hard to debug if you miss an error.

This way there is one try/catch top level and a more granular way of handling the data/business logic errors

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.