13

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:

 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
            }
          })
        })
    },
I am not able to post pictures yet, but add a link where you can look the console log where js prints the '3.' (which is placed after the await call) before '2.': Image: console

¿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.

Leo Prada
  • 160
  • 1
  • 2
  • 9

2 Answers2

22

You aren't returning anything from the loadtags method, so the code doesn't wait.

Change this:

loadtags () {
  this.$axios
    .get(...

To this:

loadtags () {
  return this.$axios
    .get(...

async/await is more or less just sugar over Promises, so returning the Promise gives you something to await in the other method.

Jared Smith
  • 19,721
  • 5
  • 45
  • 83
4

This is how I resolved this in my Vue application.

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() {
  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;
},
Leopold Kristjansson
  • 2,246
  • 28
  • 47