getn_outchea
getn_outchea

Reputation: 110

Clean up Javascript/Nodejs code

I'm new to javascript / nodejs and I'm working on some code by trying to clean it up.

I'm using the async nodejs library to deal with making the asynchronous parts of the code easier.

Right now the code looks like this:

Object.prototype.method = function(){
  var self = this; 
  // bunch of code
  async.forEach(self.someArr, function(someObj, callback){
    self.somefunc(someObj.someProp, function(err, aNewObj) {
      if (err) {
        return callback(err);
      }

      self.someOtherArr.push(aNewObj.someOtherProp);
      callback();
   });
 }, callback);
}

However, i'd like to replace the anonymous function with another named function also defined on the object's prototype. Because of the way the code is structured, I don't know how I could create a new function to pass into async.forEach while preserving the proper self value.

What I want it to look like:

AnObject.prototype.method = function(){
  var self = this; 
  // bunch of code 
  async.forEach(self.someArr, self._newMethod, callback);
}

AnObject.prototype._newMethod = function(someObj, callback){
  var self = this;
  self.somefunc(someObj.someProp, function(err, aNewObj) {
    if (err) {
      return callback(err);
    }
    self.someOtherArr.push(aNewObj.someOtherProp);
    callback();
  });
}

But that obviously doesn't work because of the context change.

Upvotes: 1

Views: 663

Answers (2)

P O'Conbhui
P O'Conbhui

Reputation: 1223

You could make this work easily enough if you change your style a bit.

AnObject = function() {
    var self = this;

    self.method = function(){
        // bunch of code 
        async.forEach(self.someArr, self._newMethod, callback);
    };

    self._newMethod = function(someObj, callback){
        self.somefunc(someObj.someProp, function(err, aNewObj) {
            if (err) {
                return callback(err);
            }
            self.someOtherArr.push(aNewObj.someOtherProp);
            callback();
        });
    };
};

Upvotes: 1

Pascal Belloncle
Pascal Belloncle

Reputation: 11389

Unless that function is defined in the same closure where self exists, you'll need to use something to proxy to it:

async.forEach(self.someArr, function(someObj, callback){
   self.somefunc(someObj.someProp, function(err, aNewObj) {
       self.otherfunc(err, aNewObj, callback);
   });
 }, callback);

Upvotes: 2

Related Questions