javascriptasynchronousvue.jsasync-awaitquasar

Async method not waiting for a function


I'm having this error and haven't got to resolve it though have researched a lot in MDN and here. I'm trying to use async and await but JavaScript 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
            }
          })
        })
    },

Here is a screenshot of the console log where JavaScript prints the '3.' (which is placed after the await call) before '2.':

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.


Solution

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