这是从使用基于 Promise 的 API 运行 Express 的 NodeJS 应用程序对路由文件中的 Controller 的调用。
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 的 Controller 的路由文件中使用它,例如:
router.get('/get-all', function(req, res) {
res.jsonPromise( CreateUserController.getAllUsers( ) );
});
最佳答案
Is it possible to pass one parameter to the
then()
that could handle both the resolve and reject?
没有。
您想要做的是定义一个可以将 promise 传递给的函数:
function jsonPromise(res, p) {
return p.then(res.jsonSuccess, res.jsonFail);
}
这样你就可以做到
router.post('/create-user', function(req, res) {
jsonPromise( res, CreateUserController.createUser( req.body.username, req.body.username ) );
});
更复杂的是采用整个 promise 返回函数并装饰它:
function jsonResponse(f) {
return function(req, res) {
Promise.resolve(req).then(f).then(res.jsonSuccess, res.jsonFail);
// similar to `f(req).…`, but catching exceptions and allowing plain return values
};
}
router.post('/create-user', jsonResponse(function(req) {
return CreateUserController.createUser( req.body.username, req.body.username );
}));
关于javascript - 然后nodejs promise 只有一个参数而不是2个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38836476/