我怎么能概括Node.js中的http响应处理程序?

我正在为节点应用程序编写一个rest api,并且我发现自己重写了如下的很多内容:

function(req, res, next) { databaseCall() .then( (results) => { if (results != null) { res.status(200).send(results); } else { res.sendStatus(404); } }) .catch(function(err) { console.log("Request error: " + err.stack); res.sendStatus(500); }) } 

我想重构响应部分,所以我可以做类似的事情

 databaseCall() .then(handleResponse) 

handleResponse将负责整个响应/捕获过程。 但我不能完全弄清楚如何做到这一点。 databaseCall方法因端点而异 – 有时需要一个参数,有时不需要。 我可以做一个通用的函数expression式,将数据库调用的结果,并将其坚持在承诺链,但我不知道如何访问该函数内的响应对象。 我知道我可以添加另一个function来结合一切,如下所示:

 function(databaseCall, parameter, req, res, next) { databaseCall(parameter) .then( (results) => { if (results != null) { res.status(200).send(results); } else { res.sendStatus(404); } }) .catch( (err) => { console.log("Request error: " + err.stack); res.sendStatus(500); }) } 

但这似乎丑陋,因为databaseCall可以有0-几个参数。 我认为有一个更优雅的解决scheme。

您可能正在考虑正确的方向,您只需要更进一步,并在通用处理程序之外保持db调用,并将其作为承诺传递

 // generic handler for db promise // the promise is created outside and passed as arg function responseFromDb(databaseCallPromise, res) { databaseCallPromise .then((results) => { if (results != null) { res.status(200).send(results); } else { res.sendStatus(404); } }) .catch((err) => { console.log(`Request error: ${err.stack}`); res.sendStatus(500); }); } // handler per request, only needs to create db call with the desired params // and pass it to the generic handler, which will take care of sending the response function(req, res, next) { responseFromDb(databaseCall(param1, param2), res) }