简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM