惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Securelist
C
CERT Recently Published Vulnerability Notes
Forbes - Security
Forbes - Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
L
LINUX DO - 最新话题
The Hacker News
The Hacker News
Google Online Security Blog
Google Online Security Blog
SecWiki News
SecWiki News
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
The Last Watchdog
The Last Watchdog
S
Schneier on Security
T
Troy Hunt's Blog
N
News | PayPal Newsroom
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Schneier on Security
Schneier on Security
P
Privacy & Cybersecurity Law Blog
T
Tor Project blog
T
Threatpost
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
A
Arctic Wolf
S
Secure Thoughts
P
Proofpoint News Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Security Latest
Security Latest
Scott Helme
Scott Helme
Security Archives - TechRepublic
Security Archives - TechRepublic
Latest news
Latest news
PCI Perspectives
PCI Perspectives
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Hacker News - Newest:
Hacker News - Newest: "LLM"
L
LINUX DO - 热门话题
P
Palo Alto Networks Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
G
GRAHAM CLULEY
V2EX - 技术
V2EX - 技术
Google DeepMind News
Google DeepMind News
Project Zero
Project Zero
V
Vulnerabilities – Threatpost
T
Threat Research - Cisco Blogs
Webroot Blog
Webroot Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
N
News and Events Feed by Topic
TaoSecurity Blog
TaoSecurity Blog
大猫的无限游戏
大猫的无限游戏
T
Tenable Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Visual Studio Blog
H
Hacker News: Front Page
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
JavaScript Promises: then(f,f) vs then(f).catch(f)
Dmitri Pavlutin · 2021-07-21 · via Dmitri Pavlutin Blog

In JavaScript, you can access the fullfillment value or the rejection reason of a promise in 2 ways.

A) Use 2 callbacks on promise.then(fn, fn):


promise

.then(success, error);


B) Or use a chain of promise.then(fn).catch(fn):


promise

.then(success)

.catch(error);


Is there any difference between the 2 approaches? Let's find out!

1. What's the same

Let's consider the callbacks we're going to use:


function success(value) {

console.log('Resolved: ', value);

}

function error(err) {

console.log('Error: ', err);

}


success() function would be called on fulfillments, while error() on rejections.

In most cases both approaches work the same way: if promise resolves successfully, then success is called in both approaches:


Promise.resolve('Hi!')

.then(success, error);

// Logs 'Resolved: Hi!'

Promise.resolve('Hi!')

.then(success)

.catch(error);

// Logs 'Resolved: Hi!'


Open the demo.

Otherwise, in case of rejection, error callback is called:


Promise.reject('Oops!')

.then(success, error);

// Logs 'Error: Oops!'

Promise.reject('Oops!')

.then(success)

.catch(error);

// Logs 'Error: Oops!'


Open the demo.

In the above examples, the behavior of both approaches is the same.

2. What's the difference

The difference is seen when the success() callback of the resolved promise returns a rejected promise. That might happen when the resolved value is invalid.

Let's modify the success callback to return a rejected promise:


function rejectSuccess(invalidValue) {

console.log('Invalid success: ', invalidValue);

return Promise.reject('Invalid!');

}


Now let's use rejectSuccess in both approaches:


Promise.resolve('Zzz!')

.then(rejectSuccess, error);

// Logs 'Invalid success: Zzzzz!'

Promise.resolve('Zzz!')

.then(rejectSuccess)

.catch(error);

// Logs 'Invalid success: Zzzzz!'

// Logs 'Error: Invalid!'


Open the demo.

Promise.resolve('Zzz!').then(rejectSuccess, error) only calls rejectSuccess, even if rejectSuccess returns a rejected promise. error callback is not invoked.

Promise.resolve('Zzz!').then(rejectSuccess).catch(error) calls rejectSuccess because the promise is resolved. But rejectSuccess returns a rejected promise, — it is caugth by .catch(error) and the error callback is invoked. That's the difference.

3. When to use

That could be useful, for example, when you perform a fetch request to get a list of items, but the list must obligatory have at least one item.

So, in case if the list is empty, you could simply reject that list:


import axios from "axios";

axios("/list.json")

.then(response => {

const list = response.data;

if (list.length === 0) {

return Promise.reject(new Error("Empty list!"));

}

return list;

})

.catch((err) => {

console.log(err);

});


Open the demo.

In the above example .catch(error) would catch the request errors and the empty list error.

4. Conclusion

The main difference between the forms promise.then(success, error) and promise.then(success).catch(error) is that in case if success callback returns a rejected promise, then only the second form is going to catch that rejection.