import { ref } from "vue";
import { ElMessage } from "element-plus";
const pageClosing = ref(false);
// 监听页面关闭事件
window.addEventListener("beforeunload", () => {
pageClosing.value = true;
});
// 维护当前的轮询控制器
let currentPollingAbortController: { cancel: () => void } | null = null;
// 轮询结果接口
interface PollingResult<T> {
result?: T;
canceled: boolean;
}
const changePayState = async (orderIdForPaying: any) => {
const pollingInterval = 3000; // 设置轮询间隔(毫秒)
let data = {
orderIdForPaying: orderIdForPaying,
};
// 启动新轮询前,取消之前的轮询
if (currentPollingAbortController) {
currentPollingAbortController.cancel();
}
// 定义轮询函数
const pollingFunction = async () => {
try {
const result = await authApi.userCheckPayingOrder(data);
return result;
} catch (error) {
return { result: null, canceled: false };
}
};
// 新建轮询
const pollingAbort = createPollingAbort();
currentPollingAbortController = pollingAbort;
const pollingResult: any = await pollUntilResult(
pollingFunction,
pollingInterval,
pollingAbort
);
console.log("pollingResult", pollingResult);
if (pollingResult.canceled) {
console.log("轮询被取消或页面关闭");
} else {
console.log("获取到结果:", pollingResult.result);
if (pollingResult.result.status === "01") {
console.log("支付成功");
clearInterval(timer);
ElMessage.success("支付成功");
userBalance();
onDialogClosed();
}
}
};
// 定义轮询函数,增加 cancel 支持
async function pollUntilResult<T>(
pollingFunction: () => Promise<T | null>,
pollingInterval: number,
abortController: { isCanceled: () => boolean }
): Promise<PollingResult<T>> {
return new Promise((resolve) => {
const poll = async () => {
if (abortController.isCanceled() || pageClosing.value) {
resolve({ canceled: true });
return;
}
const result: any = await pollingFunction();
console.log("result1111", result);
if (result.status === "01") {
resolve({ result, canceled: false });
} else {
setTimeout(poll, pollingInterval);
}
};
poll();
});
}
// 创建一个简单的取消控制器
function createPollingAbort() {
let canceled = false;
return {
cancel() {
canceled = true;
},
isCanceled() {
return canceled;
},
};
}
onUnmounted(() => {
pageClosing.value = true;
clearInterval(timer.value);
});
//多次调用轮训之后轮训最新的
根据实际情况调用changePayState方法