如何解耦和封装长的Node.js方法?

我有以下方法,简化:

var component = require('../../component.js') exports.bigMethod = function (req, res) { var connection = new sql.Connection(process.config.sql, function (err) { new sql.Request(connection) .input('input', sql.VarChar, 'value') .execute('dbo.sp1') .then(function (data) { if(data[0].length === 0) { res.status(500).send({ message: 'Some Error' }); } // set some local variable I'll use later: localVar new sql.Request(connection) .input('input1', sql.Int, req.query.input1) .input('input2', sql.Int, req.query.input2) .input('input3', sql.DateTime2, req.query.input3) .input('input4', sql.DateTime2, req.query.input4) .execute('dbo.sp2') .then(function (recordset) { json2csv( { data: recordset[0] }, function(err, data) { if (err) { res.status(500).json(err); } fs.writeFile(localVar.path, data, function (err) { if (err) { res.status(500).json(err); } try { var email = new component.Email(); email.set_callback(function (error) { if (error) { res.status(500).send({ message: 'Another error' }); } res.jsonp([]); }); email.send( localVar, { filename: localVar.name, path: localVar.path } ); } catch (e) { res.status(500).send({ message: 'Another Error' }); } }) }); }) .catch(function (err) { res.status(500).send({ message: 'Another Error' }); }); }) .catch(function (err) { res.status(500).send({ message: 'Another Error' }); }); }); }; 

正如你所看到的,这是一个很长的方法,这是一个反模式。 而且,对sp2的调用实际上是一个重复:还有另一个组件进行类似的调用,只是直接返回json2csv的结果。

现在,我不太清楚如何去分割这个方法来充分利用可重用性。 我应该封装数据库调用函数返回承诺吗? 我应该使用一些咖喱吗?

谢谢。

把你的代码划分成不同的function应该是你的首要任务 – 这个function本身就是处理太多容易分割的事情。

正如您已经猜到的那样,您可以通过分割callback和承诺来使代码的function更加清晰。

callback示例:

 new sql.Connection(..., handleSQLConnection); handleSQLConnection(error) { ... } 

承诺例子:

 doSomething .then((a) => doOtherStuff(a)) .then((b) => doSmthElse(b)); doOtherStuff(a) { ... } doSmthElse(b) { ...} 

尽pipe如此, 重构是非常有见地的。 但是你应该尽量避免上帝的function,而是写一些function来做一件事,但是做得很好 。