1

Hello I'm using sequelize and I would like to make a synchronous query, but this is made asynchronously and return an wrong response. I have this code:

function(user) {
  var allow = false;
  return User.find({ where: { id: user.id},
    include: [{
      model: Plan,
      attributes: ['id', 'name']
    }]
  }).then(function(u) {
    if(!u) throw new Error("0 user not found");
    user = u.dataValues;
    var plan = user.plan.dataValues.name;
    else if (plan == "Premium") allow = true;
    console.log("allow", allow);
    return allow;
  }).catch(function(error){
    console.log("error:::", error);
  });
}

And the console.log('allow', allow); is printing true but when I call the function, the function is returning false.

Thanks for help.

Pablo Alejandro
  • 591
  • 2
  • 10
  • 19

2 Answers2

1

You can't make asynchronous code synchronous, so you're going to have to deal with the asynchronicity.

However, it's not too difficult, since your function is returning a promise already. You can use that to pass the allow variable to a caller:

yourFunction(user).then(function(allow) {
  console.log('allow', allow);
});
robertklep
  • 198,204
  • 35
  • 394
  • 381
  • Umm thanks but, allow depends of the query... How can I wait for the response? because it is returning a different response of the query :/ – Pablo Alejandro Nov 05 '16 at 15:38
  • @PabloAlejandro right now your code is already waiting for the response (and processing it to determine the value of `allow`). You can run other queries and handle their results in a similar way. – robertklep Nov 05 '16 at 19:51
-1

I think the return allow; statement is the return value to function function(u) {} inside .then(), not the function (user) {}.

Furthermore, User.find() returns a promise. If you read about Promise, you will see there are some ways to deal with your problem. Here is one:

var myFunc = function(user, callback) {
  var allow = false;
  User.find({ where: { id: user.id},
    include: [{
      model: Plan,
      attributes: ['id', 'name']
    }]
  }).then(function(u) {
    if(!u) throw new Error("0 user not found");
      user = u.dataValues;
      var plan = user.plan.dataValues.name;
    else if (plan == "Premium") allow = true;

    callback(null, allow);

  }).catch(function(error){
    callback(error);
  });
}

Then you can use this function:

myFunc(user, function (err, allow) {
  // Do not forget to handle error

  // `allow` now could be used here
  console.log(allow);
});
notme
  • 424
  • 5
  • 14
  • Thanks, but It didn't work, I am usign [fflip](https://github.com/FredKSchott/fflip) and it return a wrong value, and I want to be able to make a query inside of the fflip function on the [criteria](https://github.com/FredKSchott/fflip#criteria) :c – Pablo Alejandro Nov 05 '16 at 15:55