سؤال

I am trying to debug some javascript code. The variable I want to debug is a JS object of objects, loaded asynchronously (ajax callback). I am debugging it outside the callback.

I am pretty sure that the problem is a race-condition problem, but I want to be sure (and it is not my question).

The problem I find when debugging is that console.log gives me an information which does not make sense with what the code is doing. Therefore, either I am missing something in the code, or the result I see in the console is the not a snapshot of the state of the variable when I runned console.log.

If it turns out to be the later, how can i get a snapshot of the state of an asynchronously loaded JS object?


This is a simplified example of the code:

//This call takes a while to invoke the callback
$.get("url",function(data){
    //Process data
    globalVariable = data; //JSON (Object of objects)
}

//Couple lines afterwards
/* This console.log shows (in Firebug's console) "Object { }" and when I click it,
   I can see the object with all its fields filled (oher objects) 
*/
console.log(globalVariable); 
for(var e in globalVariable){
     //Does not enter here, meaning that the object is empty
}
هل كانت مفيدة؟

المحلول

console.log is itself asynchronous and it shows references rather than snapshots, sometimes.

If you log an object you will get a nice clickable interface where you can inspect the object. If the object changes you will see those changes reflected there.

If you want a real snapshot you're going to have to do some serialization and serializing objects is not trivial. If your objects just are data and have no functions or references you can use JSON.stringify(obj, undefined "\t").

A smarter way is to pause your asynchronous events so you can inspect the latest state of the object.

نصائح أخرى

Write it like this instead. This way globalVariable will have the data before you act upon it.

$.get("url",function(data){
    //Process data
    globalVariable = data; //JSON (Object of objects)

    for(var e in globalVariable){
        //this will run
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top