TIL not using try/catch block with promises for error catching
POSTED ON:
TAGS: promises javascript advanced errorcatching
You shouldn't use a try/catch block inside the Promise Definition. Your promise is already doing that.
// WRONG ❌
new Promise((resolve, reject) => {
try {
const data = doThis();
// do something
resolve();
} catch (e) {
reject(e);
}
})
.then(data => console.log(data))
.catch(error => console.log(error));
// BETTER ✔️
new Promise((resolve, reject) => {
const data = doThis();
// do something
resolve()
})
.then(data => console.log(data))
.catch(error => console.log(error));
Promise itself catches all errors (even typos) within its scope without the try/catch block. It ensures that all exceptions thrown during the execution are acquired and converted to a rejected Promise.
via https://blog.bitsrc.io/5-common-mistakes-in-using-promises-bfcc4d62657f
Related TILs
Tagged: promises