Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

node.js - Correct way of handling promisses and server response

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

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.'});
  })
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...