2015-07-06 113 views
0

我在這個Meteor.js中很新。在我的Template.myTemplate.onCreated()裏面,我使用Meteor.call()調用兩個服務器方法。現在問題是在Meteor.call()中執行回調函數中的代碼,在執行onCreated函數內的剩餘代碼後執行。同樣的事情發生在幫手事件爲什麼Meteor js不能在Meteor.call上串行執行()

是不是?或者我做錯了什麼?

如果它是正確的,那麼有什麼辦法可以做代碼將連續執行?

實例讓你更好地理解:

客戶端/ myTemplate.js

Template.myTemplate.created = function(){ 
    console.log('created start'); 

    Meteor.call('myTestMethod1', function(err, res){ 
     if(res){ 
      console.log(res); 
     } 
    }); 

    Meteor.call('myTestMethod2', function(err, res){ 
     if(res){ 
      console.log(res); 
     } 
    }); 

    console.log('created end'); 
} 

服務器/ method.js

Meteor.methods({ 
    myTestMethod1 : function(){ 
     return "myTestMethod1"; 
    }, 

    myTestMethod2 : function(){ 
     return "myTestMethod2"; 
    } 
}); 

控制檯:

created start 
created end 
myTestMethod2 
myTestMethod1 

有什麼想法...

+0

我建議你搜索單詞「競賽條件」。它可以幫助你發現你的代碼正在做什麼以及爲什麼。 –

+0

@Kyll ** race condition **是'兩個線程/控件試圖同時訪問同一個數據',我知道它......但是你的想法和流星一樣是爲了防止**競爭條件** ??? – iamhimadri

+0

好吧,當你有API調用時,競爭條件是一個永久的問題。 Meteor以多種方式解決它...在服務器上,使用Fibres(異步代碼以同步樣式編寫)。在客戶端上,您可以使用無功變量。讓我寫一個答案顯示它。 –

回答

0

當您提供回調時,對Meteor方法的調用始終是異步的。請參閱official documentation

如果不提供回調,則該調用將是同步的,並且在調用完成之前,其餘代碼將不會執行。 但是,您可能無法使用同步調用獲得任何結果。

+0

流星方法僅在服務器上阻塞時,來自客戶端的呼叫永遠不會阻塞。 –

+0

@ErezHochman您的意思是客戶端的服務器API調用是同步發生的,並且在執行服務器方法時發生,儘管它有一個回調函數的剩餘代碼,然後運行回調函數。 – iamhimadri

0

解決此問題的一種方法是使用反應變量(或字典(如Session))來知道調用何時完成。因此,

Session.set('method1Completed', false); 
Session.set('method2Completed', false); 

Template.myTemplate.onCreated(function() { //Note that you should use onCreated now 
    Meteor.call('method1', function() { 
    Session.set('method1Completed', true); //You could also put your result here 
    }); 
    Meteor.call('method2', function() { 
    Session.set('method2Completed', true); 
    }); 

    Tracker.autorun(function(computation) { 
    if(Session.get('method1Completed') && Session.get('method2Completed')) { 
     //If we get in here it means both methods have completed 
     computation.stop(); //We're done, stop observing the variables 
     doStuff(); 
    } 
    } 
}