NodeJS Bluebird promise created in a handler but was not returned from it

后端 未结 1 1743
有刺的猬
有刺的猬 2021-01-14 11:55

I have the following nodejs code as an express middleware function

Middleware.is_authenticated = function(req, res, next)
{
    if(req.system_session == unde         


        
相关标签:
1条回答
  • 2021-01-14 12:43

    This comes from the mix of promise-based code (Session.validate_session) with callback-based code (next). It would be expected that the next() call either is not asynchronous (doesn't create any promises) or returns that promise, which it doesn't (blame express).

    There are two ways to avoid the warning:

    • Let express do the error handling, and call next with an error if one occurs. In this case, you can use the .asCallback method:

      Middleware.is_authenticated = function(req, res, next) {
          if (req.system_session == undefined || req.system_session.login_status == false)
              var promise = Promise.reject(new Error('invalid_session'));
          else
              var promise = Session.validate_session(req.system_session, req.ip, req.headers['user-agent']);
      
          promise.asCallback(next);
      };
      
    • As the warning explanation says, you can explicitly return null instead of returning the undefined value that next() yields:

      Middleware.is_authenticated = function(req, res, next) {
          if (req.system_session == undefined || req.system_session.login_status == false)
              var promise = Promise.reject(new Error('invalid_session'));
          else
              var promise = Session.validate_session(req.system_session, req.ip, req.headers['user-agent'])
              .catch(function(err) {
                  req.system_session.destroy();
                  throw err;
              });
      
          promise.then(function(session) {
              next();
              return null;
          }, function(err) {
              res.status(401).send({errors: true, error: err.message, session: req.system_session}).end();
          });
      };
      
    0 讨论(0)
提交回复
热议问题