0

Return a Default Value with Promises Using catch

 3 years ago
source link: https://davidwalsh.name/javascript-promise-catch
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Return a Default Value with Promises Using catch

By David Walsh on December 23, 2020  

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?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK