문제

After update my sails (0.10-rc5),

I encountered a problem in beforeCreate function :

  beforeCreate : function(values, next){

      console.log("Called beforeCreate User ");
      console.log(values);

      if(!values.password || values.password !== values.confirmation){
          return next({
              err : ["Password doesn't match password confirmation"]
          });
      }

      bcrypt.genSalt(10, function(err, salt){
        console.log("call within bcrypt");
          if (err) return next(err);
           bcrypt.hash(values.password, salt, function(err, hash){
              if(err) return next(err);
               values.password = hash;
           });
      });

      Access.findOne()
          .where({ level : values.level })
          .exec(function(err, level){
            console.log("call within findOne");
              if(err) return next(err);
              values.level = level.id;
      });

      console.log("after");    
      console.log(values);
      next();
  } 

However, the output of the above function is as following :

Called beforeCreate User 
{ firstName: 'Quad',
  lastName: 'Doe',
  email: '11@11.com',
  password: '123456',
  confirmation: '123456',
  level: 'admin',
  id: '2fa1ba1a-ae1c-4380-9107-3c1f6e8eafb3',
  online: false }
after
{ firstName: 'Quad',
  lastName: 'Doe',
  email: '11@11.com',
  password: '123456',
  confirmation: '123456',
  level: 'admin',
  id: '2fa1ba1a-ae1c-4380-9107-3c1f6e8eafb3',
  online: false }
call within bcrypt
call within findOne

As you can see, somehow bcrypt.genSalt(.....){} and Access.findOne(...){} were not called prior to after, which is supposed to.

도움이 되었습니까?

해결책

What you are seeing is asynchronous code in action...

Node/Sails does not wait for your callbacks to fire before moving on to the the next task.

You need to "nest" your callbacks so that console.log("AFTER") is called within the last callback.

Take a look at async. It's designed for these types of problems.

Or...

Look into fibers

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top