Saturday, 15 March 2014

node.js - Clean up Javascript/Nodejs code -



node.js - Clean up Javascript/Nodejs code -

i'm new javascript / nodejs , i'm working on code trying clean up.

i'm using async nodejs library deal making asynchronous parts of code easier.

right code looks 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) { homecoming callback(err); } self.someotherarr.push(anewobj.someotherprop); callback(); }); }, callback); }

however, i'd replace anonymous function named function defined on object's prototype. because of way code structured, don't know how create new function pass async.foreach while preserving proper self value.

what want 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) { homecoming callback(err); } self.someotherarr.push(anewobj.someotherprop); callback(); }); }

but doesn't work because of context change.

unless function defined in same closure self exists, you'll need utilize proxy it:

async.foreach(self.somearr, function(someobj, callback){ self.somefunc(someobj.someprop, function(err, anewobj) { self.otherfunc(err, anewobj, callback); }); }, callback);

javascript node.js asynchronous coding-style

No comments:

Post a Comment