Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Make node.js code pretty via a generator-based library

DZone's Guide to

Make node.js code pretty via a generator-based library

· Web Dev Zone
Free Resource

Should you build your own web experimentation solution? Download this whitepaper by Optimizely to find out.

The JavaScript server environment node.js has an intriguing approach to coding: Do other things while waiting for results from, say, a database. But don’t use threads to juggle those things, use continuations. This is similar to what client-side JavaScript code (such as Ajax calls) already looks like. Not having to create threads saves a lot of overhead when loads are high. Multi-core and multi-processor systems can still be supported, by scheduling one “instance” of node.js per core/processor.

The only problem with node.js code: You get one nested function expression for each outside request you make.

    io.doFirst(param1, function(foo) {
        io.doSecond(param2, function(bar) {
            // work with foo and bar
        });
    });
It is obvious that this can quickly turn ugly. Now David Herman from Mozilla has created jsTask [1], a JavaScript library that turns the above code into the much more readable code below [2].
    var foo = yield io.doFirst(param1);
    var bar = yield io.doSecond(param2);
    // work with foo and bar

This is reminiscent of multi-threading and blocking, but it works cooperatively (no preemptive multi-tasking). The similarities don’t end there: You can also do fork-join as follows:
    var [foo, bar] = yield join(io.doFirst(param1),
                                  io.doSecond(param2));

That way, you can perform both operations in parallel, but still only continue after both have finished. The library is based on generators [3], a JavaScript feature that is already in Firefox and might make it into the next version of the ECMAScript standard [4].
  1. jsTask on GitHub
  2. Who says JavaScript I/O has to be ugly?
  3. Iterators and generators [Firefox documentation]
  4. David Herman on ECMAScript.next

Implementing an Experimentation Solution: Choosing whether to build or buy?

Topics:

Published at DZone with permission of Axel Rauschmayer, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}