中断等待
2023年07月14日
前言
Promise
一经创建,无法取消。以下是手动取消 Promise
的方案
一、reject callback
let abort = () => {};
function promise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("success");
}, 8000);
abort = () => {
reject("abort");
};
});
}
promise()
.then((res) => {
console.log(res);
})
.catch((error) => {
console.log(error);
});
setTimeout(()=>{
abort();
},4000);
二、AbortController
const controller = new AbortController();
const signal = controller.signal;
function promise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("success");
}, 8000);
signal.addEventListener("abort", function () {
reject("abort");
});
});
}
promise()
.then((res) => {
console.log(res);
})
.catch((error) => {
console.log(error);
});
setTimeout(() => {
controller.abort();
}, 4000);