【问题标题】:pubnub history; wait for response酒吧历史;等待回复
【发布时间】:2016-08-16 23:59:03
【问题描述】:

我需要一些有关 pubnub 历史的帮助。我必须在 JavaScript 中检索通道的最后一条消息(对象)。所以我做了以下事情:

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();”之后的代码在我从回调函数得到答案之前执行。有没有办法强制等待回调?

【问题讨论】:

标签: javascript pubnub


【解决方案1】:

回调是异步的。这意味着您必须在回调函数中移动所有要执行的代码。

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

【讨论】:

  • 好的,我没有在示例中发布整个代码,但这意味着我必须将所有内容都放在 pubnub.history 回调中?我的意思是 pubnub.subscribe、pubnub.publish 和 EventListeners?
  • 这取决于您的代码与其他什么相关。与 Pubnub 历史无关的脚本可以放在同一个地方,但所有取决于回调结果的内容都必须放在回调函数中。
  • @TheoryX - 为您的订阅、发布等创建一些自定义函数并直接从您的历史回调或您需要的任何其他地方调用它们可能会感觉更自然。
猜你喜欢
  • 2014-01-10
  • 1970-01-01
  • 1970-01-01
  • 2011-11-04
  • 2014-06-09
  • 1970-01-01
  • 2011-07-30
  • 2019-05-02
  • 1970-01-01
相关资源
最近更新 更多