2016-08-16 100 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 - 为您的订阅,发布等创建一些自定义函数可能会感觉更自然,只需从您的历史回调或您需要的任何其他位置直接调用它们即可。 –