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

  • By
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

  • By
    Create Namespaced Classes with MooTools

    MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does.  Many developers create their classes as globals which is generally frowned up.  I mostly disagree with that stance, but each to their own.  In any event...

Incredible Demos

  • By
    NSFW Blocker Using MooTools and CSS

    One of my guilty pleasures is scoping out the latest celebrity gossip from PerezHilton.com, DListed.com, and JoBlo.com. Unfortunately, these sites occasionally post NSFW pictures which makes checking these sites on lunch a huge gamble -- a trip to HR's office could be just a click away. Since...

  • By
    Dynamic Waveform Visualizations with wavesurfer.js

    Waveform images are an awesome addition to boring audio widgets.  They can be functional as well as aesthetically pleasing, allowing users to navigate audio visually.  I recently found wavesurfer.js, an amazing waveform image utility that uses to Web Audio API to create super customizable...

Discussion

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