Async Await without try..catch

node v8.17.0
version: 2.0.0
endpointsharetweet
If you decide that you want to use async..await with promises in JS, please don't write the following code. You are converting a rejection into a specific resolution and are providing semantic value on a compile time constant.
async function donotwant() { try { const hundo = await Promise.resolve(100) await Promise.reject('whoops') return hundo; } catch (e) { return 'whoops'; } } donotwant().then(console.log)
By keeping our async function free of try catches we are able to bubble up the rejection to be handled by the caller. Line 15 in this case will never be executed because Promises can act like monads and allow short circuit logic via the reject branch.
async function foo() { const hundo = await Promise.resolve(100) await Promise.reject('whoops') await Promise.reject("you'll never catch me!") return hundo; } foo() .then(console.log) .catch(console.error)
Loading…

no comments

    sign in to comment