Skip to content

Instantly share code, notes, and snippets.

@davidkayce
Last active July 13, 2021 14:28
Show Gist options
  • Save davidkayce/b4e6bff408f019693a28c566accadea5 to your computer and use it in GitHub Desktop.
Save davidkayce/b4e6bff408f019693a28c566accadea5 to your computer and use it in GitHub Desktop.
// Safe await
// This is from a brilliant article written by David Wells on a cleaner way to maange async operations in javascript
// here: https://davidwells.io/blog/cleaner-async-await-code-without-try-catch
/* Native Error types https://mzl.la/2Veh3TR */
const nativeExceptions = [
EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError
].filter((except) => typeof except === 'function')
/* Throw native errors. ref: https://bit.ly/2VsoCGE */
function throwNative(error) {
for (const Exception of nativeExceptions) {
if (error instanceof Exception) throw error
}
}
function safeAwait(promise, finallyFunc) {
return promise.then(data => {
if (data instanceof Error) {
throwNative(data)
return [ data ]
}
return [ undefined, data ]
}).catch(error => {
throwNative(error)
return [ error ]
}).finally(() => {
if (finallyFunc && typeof finallyFunc === 'function') {
finallyFunc()
}
})
}
// Usage
async function fooBar() {
const [ error, data ] = await safeAwait(myPromiseXyz())
if (error) {
// handle error, retry, ignore etc.
}
return data
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment