Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to debug JS with generators in IntelliJ or WebStorm

I am working on a webapp in Node JS, using the Koa framework.

All the flow control is done with generators, instead of callbacks. The code looks sequential, though the actual flow is not. Anyway it looks much cleaner thant callback hell.

Here is a simple example of a controller function written with koa :

function *findUserById(userId)
{
    var user = yield getUserOrError404(userId);
    yield loadAdditionalData(user);
    yield data.users.save(user);
    return user;
}

Howeve there is one difficulty : stepping through code with yields in my IDE (IntelliJ IDEA) does not work very well. Once the execution is on the line with the yield statement, if I just "step over", the execution flows goes up the stack to koa code (this is not really the IDE's fault since it just follows the actual flow of execution of the generators, yield statements and Node event loop).

Currently I have to set a breakpoint to the next statement I want the debugger to pause, frequently the next line, and click the "Resume program" button.

It can become tedious when there are more than 2-3 yield statements.

Is there a better way (trick, plugin,...) to step through generator-heavy JS code that allow to step over a yield statement as if it were a "normal" sequential statement ?

like image 594
Pierre Henry Avatar asked Oct 20 '22 03:10

Pierre Henry


1 Answers

Sounds like a job for the Run To Cursor command - this runs effectively like a lightweight breakpoint that is removed after execution reaches the line your cursor is currently on.

See this gist for a screenshot of the button you can use for this, and a test harness file I used to check whether this works (it does; at least in PhpStorm, so I'd expect WebStorm to function the same as far as JS is concerned).

Edit : It works perfectly well in IntelliJ too. In addition to the button shown in the screenshot, you can also trigger it by right-clicking on the line and then click "Run to cursor" in the contextual menu. Or the [alt]+[F9] keyboard shortcut.

like image 95
Benjamin Avatar answered Oct 24 '22 04:10

Benjamin