1

I often see function chaines like this:

db.find('where...')
.success(function(){...})
.error(function(error){...});

I'm working on validation library for my project and i wonder how can i do chaining like that. Greetings

2 Answers 2

7

Just return the object you are operating on from your function calls.

function MyObject(x, y) {
    var self = this;
    self.x = x;
    self.y = y;
    return {
        moveLeft: function (amt) {
            self.x -= amt;
            return self;
        },
        moveRight: function (amt) {
            self.x += amt;
            return self;
        }
    }
}
var o = MyObject(0, 0);
o.moveLeft(5).moveRight(3);
Sign up to request clarification or add additional context in comments.

1 Comment

In a few cases you return a different object where it makes sense, e.g. db.find() might return a ResultSet kind of thing, but, yes, in general, just return this.
0

What you are referring is called Promise which is style of programming in Javascript to deal with asynchronous functions. More information here http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt2-practical-use

In your specific scenario, you can use when for that. Here is some example code that can get you started

function validateUnique() {
  var deferred = when.defer();
  db.query(...query to check uniqueness here.., function(error, result){
    // this is a normal callback-style function
    if (error) {
      deferred.reject(error);
    } else {
      deferred.resolve(result);
    }
  }

  return deferred.promise(); // return a Deferred object so that others can consume
}

Usage

validateUnique().done(function(result){
  // handle result here
}, function(error){
  // handle error here
})

If you want to continue the chain

validateUnique().then(anotherValidateFunction)
                .then(yetAnotherValidateFunction)
                .done(function(result){}, function(error){})

P/s: The link for when https://github.com/cujojs/when

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.