Return a Default Value with Promises Using catch
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?
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...
Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...
Background animations are an awesome touch when used correctly. In the past, I used MooTools to animate a background position. Luckily these days CSS animations are widely supported enough to rely on them to take over JavaScript-based animation tasks. The following simple CSS snippet animates...
CSS animations are right up there with sliced bread. CSS animations are efficient because they can be hardware accelerated, they require no JavaScript overhead, and they are composed of very little CSS code. Quite often we add CSS transforms to elements via CSS during...