Correct way of handling promisses and server response

前端 未结 2 1882
星月不相逢
星月不相逢 2020-12-11 12:20

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 se

2条回答
  •  一整个雨季
    2020-12-11 12:55

    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

提交回复
热议问题