Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async method not waiting for a function - VUE

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.

like image 390
Leo Prada Avatar asked Aug 24 '18 23:08

Leo Prada


People also ask

What happens if an async method is not awaited?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete.

Can we use async without await?

In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function body, however, the async function will always complete asynchronously. Code after each await expression can be thought of as existing in a .then callback.

Does async await wait?

Await: Await function is used to wait for the promise. It could be used within the async block only. It makes the code wait until the promise returns a result. It only makes the async block wait.

Is async await deprecated?

AsyncTask is used to perform time talking operations in android, but it's marked as deprecated from android 11.


2 Answers

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;
},
like image 191
Leopold Kristjansson Avatar answered Sep 18 '22 19:09

Leopold Kristjansson


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.

like image 23
Jared Smith Avatar answered Sep 16 '22 19:09

Jared Smith