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
    I’m an Impostor

    This is the hardest thing I've ever had to write, much less admit to myself.  I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life.  All of those feelings were very...

  • By
    6 Things You Didn’t Know About Firefox OS

    Firefox OS is all over the tech news and for good reason:  Mozilla's finally given web developers the platform that they need to create apps the way they've been creating them for years -- with CSS, HTML, and JavaScript.  Firefox OS has been rapidly improving...

Incredible Demos

  • By
    Sexy Opacity Animation with MooTools or jQuery

    A big part of the sexiness that is Apple software is Apple's use of opacity. Like seemingly every other Apple user interface technique, it needs to be ported to the web (</fanboy>). I've put together an example of a sexy opacity animation technique...

  • By
    Smooth Scrolling with MooTools Fx.SmoothScroll

    I get quite a few support requests for my previous MooTools SmoothScroll article and the issue usually boils down to the fact that SmoothScroll has become Fx.SmoothScroll. Here's a simple usage of Fx.SmoothScroll. The HTML The only HTML requirement for Fx.SmoothScroll is that all named...

Discussion

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