2016-08-16 105 views
1

我需要一些關於pubnub歷史的幫助。我必須在JavaScript中檢索頻道的最後一條消息(對象)。所以,我做到以下幾點:pubnub history;等待回覆

var vrednosti = {}; 

var debug = 1; 

getHistory = function(){ 
    pubnub.history({ 
     channel: settings.channel, 
     callback: function(m){ 
      var msg = m[0]; 
      var obj = msg[0]; 
      for (var key in obj){ 
       if (Object.prototype.hasOwnProperty.call(obj, key)){ 
        if(inputs[key].id=='door') inputs[key].checked = vrednosti[key] = obj[key]; 
        else inputs[key].value = vrednosti[key] = obj[key]; 
        if(debug) console.log("history:",vrednosti) 
       } 
      }   
     }, 
    count : 1, 
    }); 
} 

getHistory(); 

console.log("recorded history in var vrednosti!", vrednosti) 

setTimeout(function(){ 
    if(debug) console.log("recorded history in var vrednosti!", vrednosti) 
}, 1000); 

因此,這將產生以下結果:

recorded history in var vrednosti! Object { } 
history: Object { door: true } 
history: Object { door: true, lightLiving: "844" } 
history: Object { door: true, lightLiving: "844", lightPorch: "395" } 
recorded history in var vrednosti! Object { door: true, lightLiving: "844", lightPorch: "395" } 

所以,問題是,在之後的代碼 「getHistory();」在我從回調函數獲得答案之前執行。有沒有辦法強制回撥等待?

+0

不需要。您需要使用回調或承諾。 – SLaks

+0

這是什麼意思? – TheoryX

+0

http://blog.slaks.net/2015-01-04/async-method-patterns/ – SLaks

回答

2

回調是異步的。這意味着您必須在回調函數中移動要執行的所有代碼。

var vrednosti = {}; 

var debug = 1; 

getHistory = function(){ 
    pubnub.history({ 
     channel: settings.channel, 
     callback: function(m){ 
      var msg = m[0]; 
      var obj = msg[0]; 
      for (var key in obj){ 
       if (Object.prototype.hasOwnProperty.call(obj, key)){ 
        if(inputs[key].id=='door') inputs[key].checked = vrednosti[key] = obj[key]; 
        else inputs[key].value = vrednosti[key] = obj[key]; 
        if(debug) console.log("history:",vrednosti) 
       } 
      } 

      console.log("recorded history in var vrednosti!", vrednosti) 

      setTimeout(function(){ 
       if(debug) console.log("recorded history in var vrednosti!", vrednosti) 
      }, 1000); 
     }, 
    count : 1, 
    }); 
} 

getHistory(); 
+0

好吧,我沒有發佈整個代碼的例子,但這意味着我必須把所有內容pubnub.history回電話?我的意思是說pubnub.subscribe,pubnub.publish和EventListeners? – TheoryX

+0

這取決於您的代碼與其他相關的內容。與Pubnub歷史無關的腳本可以放在同一個地方,但所有依賴於回調結果的東西都必須放在回調函數中。 – 2016-08-16 16:15:31

+0

@TheoryX - 爲您的訂閱,發佈等創建一些自定義函數可能會感覺更自然,只需從您的歷史回調或您需要的任何其他位置直接調用它們即可。 –