我使用 ExpressJS用于路由,以及 bluebird为了 promise 。 我对几条路线重复了以下代码,最后它们都具有相同的 .catch 函数,并以失败的 json 响应。
router.get('/', function(req, res) {
return somePromise
.then(function doesSomething(someVariable) {
doSomething;
})
.catch(function catchesError(err) {
return res.json({ success: false });
});
});
我想提取 catchesError 函数,但那样它就无法使用 res 对象。
有什么建议吗?
最佳答案
只需创建一个函数并将 res
对象作为参数传递并返回一个函数。
function makeErrorCatcher(res) {
return function catchesError(err) {
return res.json({
success: false
});
}
}
router.get('/', function (req, res) {
return somePromise
.then(function doesSomething(someVariable) {
doSomething;
})
.catch(makeErrorCatcher(res));
});
关于node.js - 如何重构使用相同函数但在调用函数中还包含变量的 promise catch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29747115/