GaoLi's Blog

创建可以撤消的 Promise

如果你在 React 开发过程中使用 ES6 Promise 异步获取数据然后通过 setState 方法改变组件状态,那么你应该在 componentWillUnmount 时将未完成的 Promise 撤消,否则在组件被移除后再进行 setState 操作会遇到警告。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function createCancelablePromise(promise) {
let isCanceled = false;
const cancelablePromise = new Promise((resolve, reject) => {
promise
.then((value) => {
isCanceled ? reject({ isCanceled: true }) : resolve(value);
})
.catch((error) => {
isCanceled ? reject({ isCanceled: true }) : reject(error);
});
});
return {
promise: cancelablePromise,
cancel() {
isCanceled = true;
}
};
}
export default createCancelablePromise;

使用 createCancelablePromise 为你的 Promise 添加撤消方法,具体使用如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import createCancelablePromise from 'createCancelablePromise';
const promise = new Promise((resolve, reject) => {
setTimeout(resolve, 1000);
});
const cancelablePromise = createCancelablePromise(promise);
cancelablePromise
.promise
.then((value) => {
console.log('resolved');
})
.catch((error) => {
console.log(error);
});
cancelablePromise.cancel();

参考文章:

isMounted is an Antipattern