Today I Learned - Rocky Kev

TIL not using try/catch block with promises for error catching

POSTED ON:

TAGS:

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:

TIL functional async/await

PLACEHOLDER

TIL not using try/catch block with promises for error catching

You shouldn't use a try/catch block inside the Promise Definition. Your promise is already doing that.

TIL AggregateError

I heard the term AggregateError in relations to 'Promise.Any', So it's several errors wrapped in a array. That's all.