Browse Source

Update blog post which creates unhandled promise rejection (#9668)

* Update 2015-12-16-ismounted-antipattern.md

In case anybody else stumbles across this old blog post, I wanted to submit a patch to help with unhandled rejections.  

`#then` and `#catch` each return new Promise instances, so here we actually create two new promises (that aren't assigned).  If the argument promise to `#makeCancelable` rejects, the promise created by `#then` will be an unhandled rejection, which in Node 7 will be an uncaught error.  

By using the second argument of `#then` to handle rejections instead, we don't need to worry about the runtime finding any unhandled rejections here.

* Style updates

* Add update notice
main
Will Myers 8 years ago
committed by Dan Abramov
parent
commit
35bb6edcbb
  1. 12
      _posts/2015-12-16-ismounted-antipattern.md

12
_posts/2015-12-16-ismounted-antipattern.md

@ -54,18 +54,16 @@ cancelablePromise
cancelablePromise.cancel(); // Cancel the promise
```
Where `makeCancelable` is [defined by @istarkov](https://github.com/facebook/react/issues/5465#issuecomment-157888325) as:
Where `makeCancelable` was originally [defined by @istarkov](https://github.com/facebook/react/issues/5465#issuecomment-157888325) as:
```js
const makeCancelable = (promise) => {
let hasCanceled_ = false;
const wrappedPromise = new Promise((resolve, reject) => {
promise.then((val) =>
hasCanceled_ ? reject({isCanceled: true}) : resolve(val)
);
promise.catch((error) =>
hasCanceled_ ? reject({isCanceled: true}) : reject(error)
promise.then(
val => hasCanceled_ ? reject({isCanceled: true}) : resolve(val),
error => hasCanceled_ ? reject({isCanceled: true}) : reject(error)
);
});
@ -78,3 +76,5 @@ const makeCancelable = (promise) => {
};
```
As an added bonus for getting your code cleaned up early, getting rid of `isMounted()` makes it one step easier for you to upgrade to ES6 classes, where using `isMounted()` is already prohibited. Happy coding!
* _Update 2017-05-12: altered `#makeCancelable` implementation so rejected promises won't go uncaught._

Loading…
Cancel
Save