2016-08-01 5 views
0

関数/メソッドを順次実行する際にvuejsに問題があります。 私はのような3つの機能を持っている:私はMethodCMethodAが完全に実行された後this.MethodB()を実行したいと思いますvuejsで関数を順番に呼び出す

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(); 
} 

。これどうやってするの?

+0

私はあなたの質問を編集しました。「MethodC」と書かれましたが、あなたはどういう意味だったのか分かりません。お互いに循環的に依存している場合、どのように他のメソッドの前後に 'メソッド'を実行すると思いますか? – gurghet

+0

私は 'Promises '(https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise)を' .then'と組み合わせて呼び出しを連鎖させます。 – Elfayer

答えて

2

あなたはJavascriptを使用することができますがVue.js方法と約束:

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 
} 

を今、methodAとmethodBが終了している場合にのみ、methodCを実行するために、あなたは約束.thenを使用し、それらを一緒に連鎖することができます。例の場合:

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(); 
    }); 
} 

注:AJAXは、methodAまたはmethodB以内に呼び出す実行している場合、あなたは応答を受け取るだけの約束を解決することを確認してください。あなたの例:

this.$http.get('api/getvalue').then(function(response){ 
    ... 
    resolve('My method is now complete'); 
} 
+0

あなたがおかげでありがとう!!!、あなたが示唆したように試してみます。 –

+0

@TashTobgayあなたは歓迎です:) Javascriptの約束は、非同期コードの制御に最適です。 – crabbly

関連する問題