javascript - 在对话框关闭时取消异步状态更改
问题描述
我正在使用 Vue 并有一个对话框来获取一些数据,然后在完成时呈现它。但是,如果用户在获取完成之前手动关闭对话框,我想忽略来自异步调用的所有状态更新,以避免由它们引起的错误,然后立即再次打开对话框。
有没有更清洁的方法来处理这个问题?在不同的块中检查一个令牌三次对我来说似乎很难看。还是我完全以错误的方式解决这个问题?
// 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()
}
这可以让您将您的“中止”标志封装到一个上下文中,您可以使用该上下文来解决问题,或者执行您需要执行的任何其他操作。希望这会有所帮助。
推荐阅读
- python-3.x - 将包含mp3歌曲的python文件转换为可执行文件
- swift - swiftui为什么不能分配可选?
- mapbox - 添加 Maki 图标而不是 Mapbox 地理编码器标记
- ruby-on-rails - 如何在postgresql rails中搜索具有多个值的数组列
- html - Angular如何使表头变粘
- javascript - Sendgrid API:如何发送带有单个模板数据的批量电子邮件?
- python - TypeError: 预期的 str、bytes 或 os.PathLike 对象,
- powerbi - Power BI - DAX - 将 30 分钟添加到由 DateDiff 创建的度量
- python - odoo 12 中的相关 res_partner
- mongodb - $lookup 后 MongoDB 的 $count 非常慢