多态性nodeJS

我用nodeJS开发了一个平静的API。

exports.postCreature = function (req, res) { var creature = new Creature({ name: req.body.name, id_user: req.user._id }); creature.save(function (err) { if (err) res.status(400).send(Error.setError('impossible to save the your creature', err)); else res.status(201).send(); }); }; //CODE DUPLICATE exports.createCreature = function(user, callback) { console.log('Creature created'); var creature = new Creature({ name: user.username, id_user: user._id }); creature.save(function (err) { if (err) callback(err, null); else callback(null, creature); }); } 

这两个函数执行相同的代码,但不具有相同的参数。 我想避免重复我的代码。

如何才能避免重复我的代码?

       

网上收集的解决方案 "多态性nodeJS"

我会创build另一个函数来处理冗余:

 function createCreature (creatureName, user, callback) { console.log('Creature created'); var creature = new Creature({ name: creatureName, id_user: user._id }); creature.save(function (err, creature) { if (err) callback(err, null); else callback(null, creature); }); } 

然后在你的其他function:

 exports.postCreature = function (req, res) { createCreature(req.body.name, req.user, function (err, creature) { if (err) res.status(400).send(Error.setError('impossible to save the your creature', err)); else res.status(201).send(); }; }; exports.createCreature = function(user, callback) { console.log('Creature created'); createCreature (user.username, user, callback); }