【发布时间】: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