-->

pubnub history; wait for response

2019-07-27 09:00发布

问题:

I would need some help with pubnub history. I have to retrive last message (object) of the channel in JavaScript. So I do the following:

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

So this produces the following result:

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" }

So the problem is, that code after the "getHistory();" is executed before I get an answer from callback function. Is there a way to force the wait on callback?

回答1:

Callbacks are asynchronous. It means that you must move all code you want to execute after in callback function.

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