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 […]

The post Return a Default Value with Promises Using catch appeared first on David Walsh Blog.


This content originally appeared on David Walsh Blog and was authored by David Walsh

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?

The post Return a Default Value with Promises Using catch appeared first on David Walsh Blog.


This content originally appeared on David Walsh Blog and was authored by David Walsh


Print Share Comment Cite Upload Translate Updates
APA

David Walsh | Sciencx (2020-12-23T12:28:12+00:00) Return a Default Value with Promises Using catch. Retrieved from https://www.scien.cx/2020/12/23/return-a-default-value-with-promises-using-catch/

MLA
" » Return a Default Value with Promises Using catch." David Walsh | Sciencx - Wednesday December 23, 2020, https://www.scien.cx/2020/12/23/return-a-default-value-with-promises-using-catch/
HARVARD
David Walsh | Sciencx Wednesday December 23, 2020 » Return a Default Value with Promises Using catch., viewed ,<https://www.scien.cx/2020/12/23/return-a-default-value-with-promises-using-catch/>
VANCOUVER
David Walsh | Sciencx - » Return a Default Value with Promises Using catch. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2020/12/23/return-a-default-value-with-promises-using-catch/
CHICAGO
" » Return a Default Value with Promises Using catch." David Walsh | Sciencx - Accessed . https://www.scien.cx/2020/12/23/return-a-default-value-with-promises-using-catch/
IEEE
" » Return a Default Value with Promises Using catch." David Walsh | Sciencx [Online]. Available: https://www.scien.cx/2020/12/23/return-a-default-value-with-promises-using-catch/. [Accessed: ]
rf:citation
» Return a Default Value with Promises Using catch | David Walsh | Sciencx | https://www.scien.cx/2020/12/23/return-a-default-value-with-promises-using-catch/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.