RlyDontKnow
RlyDontKnow

Reputation: 129

Javascript Function Chaining

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

Upvotes: 1

Views: 213

Answers (2)

Tan Nguyen
Tan Nguyen

Reputation: 3354

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

Upvotes: 0

JDwyer
JDwyer

Reputation: 844

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);

Upvotes: 7

Related Questions