处理承诺和服务器响应的正确方法 [英] Correct way of handling promisses and server response

查看:106
本文介绍了处理承诺和服务器响应的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试改进node.js/sail.js中的代码,并且正在反对服务器响应.

I am trying to improve my code in node.js / sail.js and I am fighting server response in promisses.

当您查看第一个.then函数时,可以看到该方法在forbidden accessnotFound的情况下返回false.然后,在接下来的.then函数中,我必须检查返回类型是否为=== false才能跳至该节并避免两次发送http标头.是否可以通过某种方式加以改进,以防万一失败时跳过所有接下来的.then方法?我可以在最后一个.catch中抛出一个异常,但随后必须有一个case才能在所有可能的状态之间切换. (即禁止,serverError甚至找不到)

When you look at the first .then function you can see that method returns false in case of forbidden access or notFound. Then, in the next .then functions I must check if the return type is === false to skip to section and avoid sending http headers twice. Can this be improved somehow, to skip all next .then methods in case of failure? I can throw an Exception to go in the last .catch but then there must be a case to switch between all possible states. (i.e. forbidden, serverError or even not found)

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.'});
  })

推荐答案

如果要这样做,首先我要分离逻辑和接收/发送功能.其次,我指定错误代码列表.就像这样:

If I would do this, first I seperate logic and receving/sending function. Second I specify listing of error codes. And it will be like that:

/*
 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);
        }
      });
  }
};

在我使用开关的情况下,我认为选择正确的响应是更好的方法,但是这次我没有任何想法

In case where I use switch I think it is better way to select right response but on this time I haven't any idea

这篇关于处理承诺和服务器响应的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆