我正在尝试改进 node.js/sail.js 中的代码,并且我正在与 promise 中的服务器响应作斗争。
当您查看第一个 .then
函数时,您可以看到该方法在禁止访问
或notFound
的情况下返回false
。然后,在下一个 .then
函数中,我必须检查返回类型是否为 === false
以跳至部分并避免发送 http header 两次。是否可以以某种方式改进,以在失败时跳过所有接下来的 .then
方法?我可以在最后一个 .catch
中抛出异常,但随后必须有一个 case
在所有可能的状态之间切换。 (即禁止、服务器错误甚至未找到)
Notification.findOne({id: req.param('id')})
.then(function(notification) {
if (!notification) {
res.notFound();
return false;
}
if (notification.triggeredBy != req.session.user.id) {
res.forbidden();
return false;
}
return notification;
})
.then(function(notification) {
if (notification === false) {
return false;
}
return Notification.update(notification.id, actionUtil.parseValues(req));
})
.then(function(notification) {
if (notification === false) {
return false;
}
res.json(notification);
})
.catch(function(err) {
sails.log(err);
res.serverError({message: 'A server error occurred.'});
})
最佳答案
如果我要这样做,首先我分离逻辑和接收/发送功能。其次,我指定错误代码列表。它会是这样的:
NotificationService.js
/*
Listing of error codes: {
* [1] Object not found
* [2] Forbidden
* [3] Server error
}
*/
module.exports = {
nameOfMethod: function(ID, sessionID) {
return new Promise(function(resolve, reject) {
Notification.findOne({ id: ID })
.then(function(notification) {
if (!notification) return reject({ error_code: 1 });
if (notification.triggeredBy !== sessionID) return reject({ error_code: 2 });
Notification.update(notification.id, actionUtil.parseValues(req))
.then(function(notification) {
return resolve(notification); // finally return our notification
})
.catch(function(err) {
sails.log.error(err); // It's good when log is classified. In this case is error
return reject({ message: 'A server error occurred.' });
});
})
.catch(function(err) {
sails.log.error(err);
return reject({ message: 'A server error occurred.' });
});
});
}
};
NotificationController.js
module.exports = {
notifyMe: function(req, res) {
const ID = req.param('id'), sessionID = req.session.user.id;
NotificationService.nameOfMethod(ID, sessionID)
.then(function(notification) {
return res.send(notification);
})
.catch(function(err) {
switch (err.error_code) {
case 1:
return res.notFound(err);
case 2:
return res.forbidden(err);
default:
return res.serverError(err);
}
});
}
};
如果我使用 switch,我认为这是选择正确响应的更好方法,但这次我不知道
关于node.js - 处理 promise 和服务器响应的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39661064/