Created
August 23, 2019 15:43
-
-
Save mir4ef/9c8cc4eda302500edd92ae33fb6d6149 to your computer and use it in GitHub Desktop.
async/await utility function for more elegant handling of failures rather than adding try/catch blocks everywhere. This allows us to also know what exactly failed.
This file contains 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
// async/await utility function for more elegant handling of failures | |
const asyncAwaitHandler = promise => { | |
return promise | |
.then(response => ({ error: null, response })) | |
.catch(error => Promise.resolve({ error, response: null })); | |
}; | |
// example promise | |
const myPromise = (errorMe) => { | |
if (errorMe) { | |
return Promise.reject('error occurred'); | |
} | |
return Promise.resolve('success'); | |
}; | |
// usage of the utility function | |
const usage = async shouldIThrow => { | |
const data = await asyncAwaitHandler(myPromise(shouldIThrow)); | |
if (data.error) { | |
console.log(data.error); | |
} else { | |
console.log(data.response); | |
} | |
// or we can use destructuring | |
/** | |
const { error, response } = await asyncAwaitHandler(myPromise(shouldIThrow)); | |
if (error) { | |
console.log(error); | |
} else { | |
console.log(response); | |
} | |
**/ | |
}; | |
usage(); // prints 'success' | |
usage('throw me'); // prints 'error occurred' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment