1.0.2 • Published 3 years ago
abort-promise v1.0.2
AbortPromise
generator 可以用于暂停取消函数的执行,下一次在调用这个方法的时候取消之前的异步操作。
安装
npm install --save abort-promise
demo
import AbortPromise from 'abort-promise';
function wait(time = 0) {
return new Promise(resolve => setTimeout(resolve, time));
}
// 仅仅只是多了一个 abort 方法,调用即可 promise.abort('取消了') 进行取消;
// new Promise 改为 new AbortPromise,其他用法和promise保持一致
// async 改为 function*,await 改为 yield
const promise = new AbortPromise(function* (resolve, reject) {
// 模拟接口请求
yield wait(1000); // 模拟请求数据
console.log(1);
// 模拟请求数据
const result = yield new Promise(async resolve => {
await wait(1000);
resolve('我是数据');
});
console.log(result);
yield wait(1000); // 模拟请求数据
console.log(2);
yield wait(1000); // 模拟请求数据
console.log(3);
yield wait(1000); // 模拟请求数据
resolve('成功');
});
// promise 正常逻辑
// 不要放在上面进行链式调用,因为then方法会返回一个新的promise,新的没有 abort 方法
promise.then((data) => {
console.log(data);
}).catch((data) => {
console.log(data);
}).finally(() => {
console.log('执行完毕');
});
// 等待三秒后
setTimeout(() => {
// 调用取消方法
promise.abort('取消了'); // 这个参数会传入promise.catch方法
}, 3100);
React 中使用
import AbortPromise from 'abort-promise';
function wait(time = 0) {
return new Promise(resolve => setTimeout(resolve, time));
}
class Index extends PureComponent {
...//其他代码
fetch = () => {
const that = this; // 需要保存this
this.promise?.abort(); // 取消之前的,不会去请求后续的接口,也不会调用到 setState
this.promise = new AbortPromise(function* () {
const result1 = yield wait(500); // 模拟请求数据
const result2 = yield wait(500); // 模拟请求数据
const result3 = yield wait(500); // 模拟请求数据
that.setState({ result1, result2, result3 });
});
}
...// 其他代码
}
调用下次方法之前取消之前的,调用 abort 方法
let promise;
promise?.abort();
promise = new AbortPromise(function* (resolve) {
...其他逻辑
});
api
const promise = new AbortPromise(function* (resolve, reject) {
yield console.log(1);
});
promise?.abort();