2

I am having some problem in vuejs in executing a function/method sequentially. I have three functions like:

MethodA: function(){
    if(x = 1){
        value1 = 2;
    }

    if (x ==2){
         value2 = 4;
    }

    this.MethodB();
}

MethodB: function(){
    Total value = value1 + value2;
}

MethodC: function (){
    this.$http.get('api/getvalue').then(function(response){
        this.set('somedata', response.data);

        response.data.forEach(para){
            if(para.id == 1){
                this.MethodA();
            }
            if(para.id == 2){
                this.MethodA();
            }
        }
    });
}

ready: function(){
    this.MethodC();
}

I would like to execute this.MethodB() only after MethodC and MethodA has completely executed. How can I do this?

2
  • I edited your question writing MethodC but now I'm not sure what you meant. Could you please explain how do you expect to have any Method to execute before/after the others if they are circularly dependent on each other? Commented Aug 1, 2016 at 10:43
  • I'd use Promise with .then to chain the calls. Commented Aug 1, 2016 at 12:15

1 Answer 1

6

You can use Javascript Promises with Vue.js methods:

methodA: function() {
    return new Promise(function(resolve, reject) {
       //run all your methodA code here
       ...

       resolve('MethodA finished');
    });
},
methodB: function() {
    return new Promise(function(resolve, reject) {
       //run all your methodB code here
       ...

       resolve('MethodB finished');
    });
},
methodC: function() {
    //run your methodC code
}

Now, to run methodC only when methodA and methodB are finished, you can use the promises .then and chain them together. For ex:

ready: function() {
    //save `this` to a variable just to make it easier to be accessed within the chain
    let self = this;

    //run methodA, then methodB...only then, methodC
    self.methodA.then(function(resultA) {
        console.log(resultA);
        return self.methodB();
    }).then(function(resultB) {
        console.log(resultB);
        self.methodC();
    });
}

Note: if you running AJAX calls within methodA or methodB, make sure to resolve the promise only when you receive a response. In your ex.:

this.$http.get('api/getvalue').then(function(response){ 
    ...
    resolve('My method is now complete'); 
}
Sign up to request clarification or add additional context in comments.

1 Comment

@TashiTobgay You are welcome :) Javascript promises are great for async code control.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.