node.js - 如何重构使用相同函数但在调用函数中还包含变量的 promise catch?

标签 node.js express promise bluebird

我使用 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/

相关文章:

javascript - 如何在 Node 5.6.0 环境中运行 Node 6 npm 包?

node.js - 嵌套循环续写 Node.js 中的每条记录

javascript - 循环调用api直到响应成功

javascript - 如何同时处理多个 Promise

node.js - next() 在 Express 4 中不起作用

javascript - 如何使用 webpack 构建 requirejs 应用程序?

node.js - 如何在 openshift 上安装全局 Node 模块?

javascript - req.getValidationErrors() 不是一个函数

sql - 与 Sequelize 的事务不起作用

javascript - 在我的案例中如何发出多个 http 请求