debugging JS file - Client Side code

故事扮演 提交于 2019-12-12 01:38:49

问题


Is there any easy way in which we can know the sequence in which methods are called in runtime?

Example: In my JS File, I have around 15 methods. There are some Asynchronous calls. With Async calls we never know the sequence in which they are called and executed. So : I want to know, if there is a way in which we can debug (using developer tools, IE\Chrome\FF) .. any tool which tells me which async call was called first and the order in which they are called.

Thanks.


回答1:


Using Chrome developer tools, you can use the Sources panel to debug javascript.

On the right side, you can add breakpoints for various types of events including XHR Breakpoints.

The execution will stop when the breakpoint is triggered and you can step through the execution flow.

I'm pretty sure Firefox and IE have similar tools.




回答2:


As ryan S suggested, using console.log can be a way of checking the sequence of code execution. So you can add console.log("1: [description]").




回答3:


Beside the given answers, you can also write a utility that will make wrap the methods of an object with logging:

It would be like this:

function addLogging(object) {   
    Object.keys(object).forEach(function (key) {
        if (typeof object[key] === 'function') {
            var originalFn = object[key];
            object[key] = function () {
                console.log('before calling', key);
                var result = originalFn.apply(this, arguments);
                console.log('after calling', key);
                return result;
            }
        }
    });
}

You can use lodash wrap method to help you.

Long ago I have answered a question regarding something similar like the above code: jQuery logger plugin

It didn't handle constructors perfectly, so it had problems like that. Here's the fixed resulting code.

You can also have a look at sinon.js, it provides spies and it can determine order of call of spied functions. But it might be a bit too much for just this, and it's might slow things down a little.

This method is a common thing done in aspect oriented programming. You can search about it and maybe try to use a AOP library. meld is a popular one.

Also instead of console.log in chrome you can use console.timeline, which gives you great visibility if used correctly.



来源:https://stackoverflow.com/questions/23762311/debugging-js-file-client-side-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!