Javascript 不等待函数的异步方法 - VUE
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/52012757/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Async method not waiting for a function - VUE
提问by Leo Prada
i'm having this error and haven't got to resolve it though have researched a lot in MDN and here. As title saysinto VUE i'm trying to use async and await but js is not waiting the 'await' function to end. Here it is:
我遇到了这个错误,虽然在 MDN 和这里研究了很多,但还没有解决它。正如标题所说的 VUE,我正在尝试使用 async 和 await,但 js 没有等待“await”函数结束。这里是:
 methods: {
    async search (terms, done) {
      console.log('1.')
      this.filter = this.$refs.chipsInput.input
      await this.loadtags()
      console.log('3.')
      done(this.tagsList)
    },
    loadtags () {
      this.$axios
        .get('/api/tags/?id__icontains=&id=&name__icontains=' + this.filter + '&name=&ordering=name&page_size=20')
        .then(response => {
          console.log('2.', response.data.results)
          let temp = response.data.results
          this.tagsList = temp.map(obj => {
            return {
              name: obj.name,
              label: obj.name,
              value: obj.name,
              idField: obj.id
            }
          })
        })
    },?What am i doing wrong? already tried modifying the await like this: let foo = await this.loadtags() and including a 'return 0' at the end of loadtags function but didn't work for me. Probably is a dumb thing, excuse me for that.
?我究竟做错了什么?已经尝试像这样修改等待: let foo = await this.loadtags() 并在 loadtags 函数的末尾包含一个“返回 0”,但对我不起作用。可能是一件愚蠢的事情,请原谅我。
回答by Jared Smith
You aren't returning anything from the loadtagsmethod, so the code doesn't wait.
您不会从该loadtags方法返回任何内容,因此代码不会等待。
Change this:
改变这个:
loadtags () {
  this.$axios
    .get(...
To this:
对此:
loadtags () {
  return this.$axios
    .get(...
async/awaitis more or less just sugar over Promises, so returning the Promise gives you something to await in the other method.
async/await或多或少只是 Promises 的糖,所以返回 Promise 会给你一些在其他方法中等待的东西。
回答by Leopold Kristjansson
This is how I resolved this in my Vue application.
这就是我在 Vue 应用程序中解决此问题的方法。
Before a user submits a new "tag" with submitNewTag()I need to check if it exists already in the list of tags, using async theTagExists().
在用户提交一个新的“标签”之前,submitNewTag()我需要检查它是否已经存在于标签列表中,使用async theTagExists().
submitNewTag() {
  this.clearError();
  this.theTagExists().then((res) => {
    if (!res) {
      console.log("TAG DOES NOT EXIST, SO ADD IT TO THE DATABASE");
      this.saveTagToDatabase();
    }
  });
},
async theTagExists() {
  console.log("CHECKING IF A TAG EXISTS");
  await axios.get(`${this.apiUrl}/alltags`).then((res) => {
    console.log("CHECKING IS DONE");
    this.tagExists = res.data.allTags.some(
      res =>
        res.name.trim().toLowerCase() ===
        this.newTag.tagName.trim().toLowerCase()
    );
  });
  console.log("RETURN THE RESULT");
  return this.tagExists;
},

