首页 > 解决方案 > 在对话框关闭时取消异步状态更改

问题描述

我正在使用 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;
}

标签: javascriptvue.js

解决方案


您也许可以使用生成器来完成与您想要的类似的事情。下面是一个例子:

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()
}

这可以让您将您的“中止”标志封装到一个上下文中,您可以使用该上下文来解决问题,或者执行您需要执行的任何其他操作。希望这会有所帮助。


推荐阅读