링크모음/React
React 사용시 Promise Cancel() 하는 경우
행복한 수지아빠
2018. 5. 12. 16:56
반응형
While there isn't a standard way of doing this in ES6, there is a library called Bluebird to handle this.
There is also a recommended way described as part of the react documentation. It looks similar to what you have in your 2 and 3rd updates.
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)
);
});
return {
promise: wrappedPromise,
cancel() {
hasCanceled_ = true;
},
};
};
const cancelablePromise = makeCancelable(
new Promise(r => component.setState({...}}))
);
cancelablePromise
.promise
.then(() => console.log('resolved'))
.catch((reason) => console.log('isCanceled', reason.isCanceled));
cancelablePromise.cancel(); // Cancel the promise
Taken from: https://facebook.github.io/react/blog/2015/12/16/ismounted-antipattern.html
반응형