Return a Default Value with Promises Using catch
Publikováno: 23.12.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 […]
The post Return a Default Value with Promises Using catch appeared first on David Walsh Blog.
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.