javascript - How do you refactor nested callbacks and pass parameters to each function in node? -


i'm trying refactor javascript code in node, , having trouble passing parameters functions callbacks other functions. example set of callbacks:

userschema.pre("save",function(next){     var user = this;     if (!user.ismodified(value)) {return next();}     bcrypt.gensalt(10,function(err,salt){         if (err) {return next(err);}         bcrypt.hash(user.password,salt,function(err,hash){             if (err) {return next(err);}             user.password = hash;             next();         });     }); }); 

i want refactor callbacks looks cleaner , without external library async or q

userschema.pre("save",function(next){     var user = this;     if (!user.ismodified(value)) {return next();}     bcrypt.gensalt(10,saltcallback(user)); }); function saltcallback(user){     return function(err,salt){         bcrypt.hash(user,salt,hashcallback(user));     } } function hashcallback(user){     return function(err,hash){         if (err) {return next(err);}         user.password = hash;         next();     } } 

the problem i'm trying can't seem find way pass dependent parameters between functions refactoring work.

if give me pointers on that'd great

there 2 different ways of doing this. either pass both, user , next.

userschema.pre("save",function(next){     var user = this;     if (!user.ismodified(value)) {return next();}     bcrypt.gensalt(10,saltcallback(user, next)); }); function saltcallback(user, next){     return function(err,salt){         bcrypt.hash(user.password,salt,hashcallback(user, next));     } } function hashcallback(user, next){     return function(err,hash){         if (err) {return next(err);}         user.password = hash;         next();     } } 

or define 2 functions inside first function.

userschema.pre("save",function(next){     function saltcallback(err,salt){         bcrypt.hash(user.password,salt,hashcallback);     }     function hashcallback(err,hash){         if (err) {return next(err);}         user.password = hash;         next();     }     var user = this;     if (!user.ismodified(value)) {return next();}     bcrypt.gensalt(10,saltcallback); }); 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -