node.js: How do you avoid a big investment in asynchronous requests?



  • It's been a long time since studied by JS, TypeScript, node.js platform.

    The asynchronicity of entry/driving events and one-offness is a great idea, but as a classic, I'm very confused with the enriched code. I mean, designs like:

    network.receive(..., function(data) {
        if (data.command == 'logon')
            access.check('logon', function(result) {
                if (result == true) {
                    log.add('call logon')
                    db.sql('select ...', function(err, row) {
                        log.add('logon success')
                        network.send(data.address, 'success', function(res) {
                            if (res...) ...
                        }.bind(this))
                    }.bind(this))
                }
            }.bind(this))
    }.bind(this))
    

    That's the code that's a lesbian that's really annoying: And those endless binds. Of course, I took the example, but I think the complaint is clear.

    Maybe it's old habits in me? Is there any concept of code writing to make it more careful, beautiful? For example, I'm very unhappy that if I wrote on TypeScript my class and I'm calling it something like that:

    var result = new MyClass.search(...)
    

    The search method(s) will be called before the designer is completed if the designer has to use asynchronous functions. I mean, the designer hasn't fully completed the initialization of the facility yet, and someone's already calling the object's methods. Is there any way to do something like this in the implementation (single from windows API):

    search(...) {
        waitForSingleObject(event)
        ...
    }
    

    And until the designer does his job and calls for: setEvent(event) Do you want to slow down the search method? But, of course, waitForSingleObject() should be a smart function and give an understanding of the flow that, so far, you can do other things and not stop, let's say, the whole node.js platform?

    P.S. I'm sorry there's so many letters.



  • You'll be fine. https://github.com/caolan/async#waterfall :

    async.waterfall([
        function(callback) {
            callback(null, 'one', 'two');
        },
        function(arg1, arg2, callback) {
          // arg1 now equals 'one' and arg2 now equals 'two'
            callback(null, 'three');
        },
        function(arg1, callback) {
            // arg1 now equals 'three'
            callback(null, 'done');
        }
    ], function (err, result) {
        // result now equals 'done'
    });
    

    Some other methods from this library will also be necessary.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2