NodeJS:Hapi +猫鼬|返回回调不起作用

时间:2018-06-23 16:03:27

标签: node.js mongoose callback promise hapijs

我正在使用hapi和猫鼬来简化登录系统。

server.route({
method: 'POST',
path: '/register',
config: {
  handler: (request, h) => {
    const username = request.payload.username.toLowerCase();
    const email = request.payload.email.toLowerCase();
    const password = request.payload.password;
    const passwordconfirm = request.payload.passwordconfirm;
    if(password==passwordconfirm && username && email && password) {
      var userData = {
        email: email,
        username: username,
        password: password,
        verified: false
      }
      User.create(userData, function (err, user) {
        //if there is an error about email
        if (err.toString().indexOf("email")>-1) {
          return statusGenerator(false, "Email already in use", null);
        }

        //if there is an error about email
        if (err.toString().indexOf("username")>-1) {
          return statusGenerator(false, "Username already in use", null);
        }

        //send email to specified email
        return statusGenerator(true,"Confirm your email",null);
      });
     }
   }
 }
});

statusGenerator()生成一个JSON,该JSON应该作为响应发送回。 在hapi中,我可以从处理程序中返回以实现此目的,但我不知道如何从回调中获取该值并作为响应发送。 这是错误。

Debug: internal, implementation, error
Error: handler method did not return a value, a promise, or throw an error
at module.exports.internals.Manager.execute (c:\Users\me\path\node_modules\hapi\lib\toolkit.js:52:29)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)

1 个答案:

答案 0 :(得分:0)

我用Promise解决了它:

     return new Promise((resolve) => {
        User.create(userData, function (err, user) {
          if(err)
          {
            if (err.toString().indexOf("email")>-1) {
              resolve(statusGenerator(false, "Email already in use", null));
            }

            if (err.toString().indexOf("username")>-1) {
              resolve(statusGenerator(false, "Username already in use", null));
            }
          }
          //send email to specified email
          resolve(statusGenerator(true,"Confirm your email",null));
        });
      });