Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This is a bit annoying since if you want to make three async requests you have to write the following

Well, beyond a style issue. You can unfold the events and make it a lot less "annoying".

Consider,

var cb1 = function() {

}

var cb2 = function() {

  req(cb1);
}

var cb3 = function() {

  req(cb2);
}

req(cb3);

It's a lot cleaner and it looks like a state machine (and kind of looks like erlang/message passing).



More than anything, the fact that node makes you dwell on this AT ALL is a bad sign. It's like wondering if your indentation is causing bugs.


Another way is to have an array of functions and just loop||recurse through them. This gives the illusion of serial execution.

There are actually a number of other ways to get around the function nesting issue as well.


Tip: make sure you hit space two times before writing your code so it renders correctly:

var not_formatted;

  var formatted;


That's actually quite a painful way to write async code because the control flow is now inside the functions. That makes it very hard to perform refactoring.

Might I suggest you take a look at my preferred solution for this,

    var cb1 = function(callback) {
        callback();
    }

    var cb2 = function(callback) {
        req(function() {
            callback();
        });
    }

    var cb3 = function(callback) {
        req(function() {
            callback();
        });
    }

    sequence([
        cb1,
        cb2,
        cb3
        ]);
The sequencer is a simple lib function you can find at https://github.com/michiel/sequencer-js or using 'npm install sequencer'


I've actually been put off Node a little because I've not seen any examples using this style of code. I had (perhaps stupidly) assumed that the scope of a closure was necessary for a lot of Node functionality; generally speaking, are all the parameters required for interacting with Node passed via the function parameters?




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: