Javascript 在对话框关闭时取消异步状态更改
我正在使用Vue,有一个对话框,可以获取一些数据,完成后再进行渲染。但是,如果用户在提取完成之前手动关闭对话框,那么我希望忽略异步调用中的所有状态更新,以避免它们引起的错误,然后立即再次打开对话框 有没有更干净的方法来处理这个问题?在不同的街区检查一个代币三次对我来说很难看。还是我完全走错了方向Javascript 在对话框关闭时取消异步状态更改,javascript,vue.js,Javascript,Vue.js,我正在使用Vue,有一个对话框,可以获取一些数据,完成后再进行渲染。但是,如果用户在提取完成之前手动关闭对话框,那么我希望忽略异步调用中的所有状态更新,以避免它们引起的错误,然后立即再次打开对话框 有没有更干净的方法来处理这个问题?在不同的街区检查一个代币三次对我来说很难看。还是我完全走错了方向 // A token on the Vue component instance for the most recently async call globalToken = null; priv
// A token on the Vue component instance for the most recently async call
globalToken = null;
private async fetchData() {
const token = new Object();
try {
isFetching = true;
globalToken = token;
await fetchSomeData();
// No side effects if our async token has been revoked
if (token === globalToken) {
doStuff();
}
} catch (error) {
console.error(error)
if (token === globalToken) {
displayError();
}
} finally {
if (token === globalToken) {
this.isFetching = false;
}
}
}
openDialog() {
fetchData();
}
closeDialog() {
isFetching = false;
// Revoke the token for any pending requests
globalToken = null;
}
您可以使用生成器来完成与您想要的类似的任务。一个例子如下:
function* fetchData() {
let abort = false;
yield (async() => {
fetchSomeData().then((data) => {
if (abort) {
console.log("aborting")
return;
}
console.log("proceeding")
doStuff();
})
})();
yield abort = true;
}
const sequence = fetchData();
function openDialog() {
// This will fire the first yield in the generator, calling your async function
sequence.next()
}
function closeDialog() {
// This will fire the second yield in the generator, setting your flag
sequence.next()
}
这可以让您将“abort”标志封装到一个上下文中,您可以使用该上下文跳出,或者执行您需要执行的任何其他操作。希望这会有帮助