Firebug的的console.log:调试异步变量 [英] Firebug's console.log: debugging asynchronous variables

查看:131
本文介绍了Firebug的的console.log:调试异步变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图调试一些JavaScript code。我要调试的变量是一个对象的JS对象,异步加载(AJAX回调)。我调试它回调之外。

我是pretty确保该问题是一个竞争条件的问题,但我想肯定(它是的不是我的问题)。

我发现在调试的时候的问题是,的console.log 给我一个信息,这不符合什么code做是有意义的。因此,无论是我缺少在code的东西,或者我在控制台中看到的结果是,当我拼命地跑变量的状态不是快照的console.log

如果它原来是后来的我怎样才能得到一个异步加载JS对象状态的快照


这是一个简化例如$ C $的C

  //此调用需要一段时间才能调用回调
$获得(URL,功能(数据){
    //处理数据
    globalVariable =数据; // JSON(对象的对象)
}//两行之后
/ *这个节目的console.log(在Firebug的控制台)对象{}当我点击它,
   我可以看到该对象及其所有字段填写(oher对象)
* /
的console.log(globalVariable);
对(在globalVariable变种E){
     //不进入这里,这意味着该对象为空
}


解决方案

的console.log 本身是异步的,它显示的引用而不是快照,有时

如果你登录一个对象,你会得到一个不错的点击界面,你可以检查对象。如果对象改变了,你会看到这些变化反映在那里。

如果你想你将不得不做一些序列化一个真正的快照和序列化对象是不平凡的。如果你的对象只是有数据和没有功能或引用您可以使用 JSON.stringify(OBJ,未定义\\ t的)

一个更聪明的办法是暂停异步事件,所以你可以检查对象的最新状态。

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.

这篇关于Firebug的的console.log:调试异步变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆