Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue: How to wait until one method completes before firing another

I have two methods on my Vue instance;

const app = new Vue({
  el: '#app',
  data: {
   id: null
  },
  methods: {
   getId: function() {
     return axios.get('url')
     .then(response => response.data)
     .then(id => this.id = id)
     .catch(error => console.log(error))
   },

   foo: function() {
    console.log(this.id)
   }
 },
 mounted: function() {
 this.getId()
 this.foo()
 }
})

The console.log() logs null as the value because it runs before the response getId() has managed to set the id value. I know this because when I use Vue developer tools, the id is the actual value I was expecting rather than null.

How can I make sure getId() has set the value before running this.foo() ?

like image 426
ProEvilz Avatar asked Oct 13 '18 21:10

ProEvilz


2 Answers

You can use JavaScript promises to achieve this. The simplest way would be to use the async/await syntax ..

const app = new Vue({
  el: '#app',
  data: {
   id: null
  },
  methods: {
   getId: function() {
     return axios.get('url')
     .then(response => response.data)
     .then(id => this.id = id)
     .catch(error => console.log(error))
   },

   foo: function() {
    console.log(this.id)
   }
 },
 mounted: async function() {
   await this.getId()
   this.foo()
 }
})

Or you can go the old-fashioned way ..

const app = new Vue({
  el: '#app',
  data: {
   id: null
  },
  methods: {
   getId: function() {
     return axios.get('url')
     .then(response => response.data)
     .then(id => this.id = id)
     .catch(error => console.log(error))
   },

   foo: function() {
    console.log(this.id)
   }
 },
 mounted: function() {
   this.getId().then(() => this.foo())
 }
})
like image 131
Husam Ibrahim Avatar answered Oct 19 '22 18:10

Husam Ibrahim


there are a lot of things that you can do, I think it's useful to read about Promises in JS, but a simple answer for here:

const app = new Vue({
  el: '#app',
  data: {
   id: null
  },
  methods: {
       getId: function(callback) {
         return axios.get('url')
         .then(response => response.data)
         .then((id) => { 
               this.id = id
               callback()
          })
         .catch(error => console.log(error))
       },

       foo: function() {
        console.log(this.id)
       }
  },
  mounted: function() {
     this.getId(() => {
        this.foo()
     })
  }
})
like image 42
Amir Khorsandi Avatar answered Oct 19 '22 20:10

Amir Khorsandi