【发布时间】:2016-08-09 03:21:41
【问题描述】:
这是从运行 express 的 nodejs 应用程序调用路由文件中的控制器,并使用基于 promise 的 api。
router.post('/create-user', function(req, res) {
CreateUserController.createUser( req.body.username, req.body.username ).then( res.jsonSuccess, res.jsonFail );
});
如您所见,上述解析回调的最终结果命中 res.jsonSuccess,而拒绝(then 函数中的第二个参数)命中 res.jsonFail。
res.jsonSuccess 和 res.jsonFail 是该项目的自定义中间件,只需相应地格式化和记录数据。
我的问题:我想进一步简化。是否可以将一个参数传递给可以处理解析和拒绝的then()?
例如
router.post('/create-user', function(req, res) {
CreateUserController.createUser( req.body.username, req.body.username ).then( res.jsonOutDecide );
});
根据接受的答案,我能够将以下中间件放在一起:
/**
* unify the json output of any response with jsonFail and jsonSuccess methods
*/
module.exports = function(){
return function(req, res, next) {
/**
* Error json output
* @param errObj (optional)
* @returns {*}
*/
res.jsonFail = function ( errObj ) {
errObj = errObj || {};
return res.json({
success : false,
error : errObj
})
};
/**
* Success json output
* @param data
* @returns {*}
*/
res.jsonSuccess = function ( data ) {
data = data || {};
return res.json({
success: true,
data: data
});
};
/**
* Accepts a promise and passes onto the success or fail options above
* @param p
* @returns {*}
*/
res.jsonPromise = function(p) {
return p.then(res.jsonSuccess, res.jsonFail);
};
next();
};
};
现在可以很容易地在使用基于 prmoise 的控制器的路由文件中使用,例如:
router.get('/get-all', function(req, res) {
res.jsonPromise( CreateUserController.getAllUsers( ) );
});
【问题讨论】:
-
这并没有真正简化事情,也不是你想要的,但你可以做
then(res.jsonGood).catch(res.jsonBad) -
它可能会......我想知道是否有更高的配置允许所有未被第二个参数函数捕获的承诺成为一个函数。这样路由器只需要关心自己是否成功,路由器级别的失败将被捕获网捕获
-
@adam-beck 但是that's not the same thing
-
@Bergi 不知道这一点。感谢分享!
标签: javascript node.js promise