pubnub历史;等待回应

时间:2016-08-16 15:34:30

标签: javascript pubnub

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

1 个答案:

答案 0 :(得分: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();
相关问题