Return a Default Value with Promises Using catch

By  on  

Last week I tweeted all of you looking for your best JavaScript Array and Promise tricks, and as always, it didn't disappoint -- I learned quite a bit!

Today's JavaScript Promise trick is brought to you by Claudio Semeraro: how to use catch to set a default value instead of a try/catch:

// Instead of wrapping this block in a try/catch...
const result = await new Promise(
  (resolve, reject) => reject("Because Stone Cold said so")
)
// ...use catch to set the default value (100)
.catch(() => 100);

As a trick I really like what's this brings; as far as readability and maintenance, if you don't know the trick, you might get confused. What do you think?

Recent Features

Incredible Demos

  • By
    dwClickable:  Entire Block Clickable Using MooTools 1.2

    I recently received an email from a reader who was really impressed with Block Clickable, a jQuery script that took the link within a list item and made the entire list item clickable. I thought it was a neat script so I...

  • By
    Create a CSS Flipping Animation

    CSS animations are a lot of fun; the beauty of them is that through many simple properties, you can create anything from an elegant fade in to a WTF-Pixar-would-be-proud effect. One CSS effect somewhere in between is the CSS flip effect, whereby there's...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!