-
-
Save voidnerd/557861de8c204117e64a4b95672f7ddc to your computer and use it in GitHub Desktop.
Nicer try/catch for async await.
This file contains hidden or 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
/* 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) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment