Async method not waiting for a function
Asked Answered
L

2

13

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.

Likeminded answered 24/8, 2018 at 23:18 Comment(1)
You're not returning anything from loadTags to be awaited.Alic
A
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.

Alic answered 24/8, 2018 at 23:25 Comment(2)
Why not just declare async loadtags, and await this.$axios?Backbone
@Backbone you could, and probably should as it would be more consistent.Alic
B
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;
},
Bourassa answered 16/11, 2018 at 11:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.