I've been reading about the use of async/await instead of the classic .then() in Promises, but there's still something that I don't understand.
I know that you can replace the classic .then().catch() with async/await and try and catch but that will handle exceptions and rejects like they're the same.
Example:
async function func1() { return new Promise((resolve, reject) => { //throw new Error("error"); reject("rejected"); }); } async function func2() { try { const message = await func1(); console.log(message); } catch(e) { console.log(e); } } func2(); Both reject and throw new Error will fall into the catch block but Promises also has the next sintaxis:
then(funcResolve, funcReject).catch(funcCatch) but async/await treats both reject and errors as the same.
Is there any way to differentiate with async/await an error from a reject?
async/awaitwith it's own try/catch and possibly modify your error there. You could make your asynchronous functions potentially throw custom errors. If the async operations are network requests, the errors produced there will potentially have properties that non-network errors have, so you can possibly check for that.catch(func)is just a shortcut for.then(undefined, func). Promises themselves don't distinguish between "rejected because it called the reject function" and "rejected because of an exception"then(funcResolve, funcReject).catch(funcCatch)-- I believe that in that code,funcCatchwould ONLY catch errors thrown infuncReject, not errors thrown by the promise or errors thrown infuncResolvepromise.then(funcResolve, funcReject).catch(funcCatch)behaves differently than I expect. A rejection frompromisegoes tofuncReject, while an error thrown infuncResolveskipsfuncRejectand goes straight tofuncCatch. At least in Chrome