

Return a Default Value with Promises Using catch
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
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?
Recommend
-
20
published: 12 December 2019 A colleague came up to me the other day to ask me two very good questions: “Why does the AWS node sdk have this .promise() function that you can chain onto all its...
-
13
Rails has added support for adding a default value to the rich text area. To specify the default value for a rich text area, we need to pass the value in the
-
5
Caching multimethod default value dispatch Ticket CLJ-1429 started from a tweet by Anton...
-
17
How to add a default value to an existing column in a Rails migration You probably know that you can easily set a default when adding a new column in an Active Record migration. a...
-
5
In JavaScript, you can check the status of the resolved promise using 2 approaches. A) Use 2 callbacks on promise.then() — the first for fullfillment and the second for rejection: promise .then(succes...
-
6
<?xml encoding="utf-8" ??>Introduction When you deploy a Vultr virtual cloud server, it receives an IP address assignment automatically with DHCP. Usually, you do not need to change the network...
-
7
How the metaverse is looking to transform the workplace with virtual reality technology in the gaming space so far, with content
-
2
【踩坑】.NET异步方法不标记async,Task<int> 返回值 return default问题 ...
-
9
Conversation Member This ensures...
-
4
'return await' in a try/catch This might sound weird to you, the first thing that comes to mind is: 'Eslint will tell me to remove the await, there is no need for an...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK