我需要一些关于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();”在我从回调函数获得答案之前执行。有没有办法强制回拨等待?
不需要。您需要使用回调或承诺。 – SLaks
这是什么意思? – TheoryX
http://blog.slaks.net/2015-01-04/async-method-patterns/ – SLaks