我需要一些關於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