【问题标题】:Sequelize synchronous ORMSequelize 同步 ORM
【发布时间】:2017-03-18 23:28:05
【问题描述】:

您好,我正在使用 sequelize,我想进行同步查询,但这是异步进行的,并返回错误的响应。 我有这个代码:

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);
  });
}

console.log('allow', allow); 正在打印true,但是当我调用该函数时,该函数正在返回false

感谢您的帮助。

【问题讨论】:

标签: node.js sequelize.js


【解决方案1】:

您无法使异步代码同步,因此您将不得不处理异步性。

然而,这并不是困难,因为你的函数已经返回了一个承诺。您可以使用它将allow 变量传递给调用者:

yourFunction(user).then(function(allow) {
  console.log('allow', allow);
});

【讨论】:

  • 嗯,谢谢,但是,允许取决于查询...我如何等待响应?因为它返回查询的不同响应:/
  • @PabloAlejandro 现在您的代码已经在等待响应(并处理它以确定allow 的值)。您可以运行其他查询并以类似方式处理其结果。
【解决方案2】:

我认为return allow; 语句是.then() 内部函数function(u) {} 的返回值,而不是function (user) {}

此外,User.find() 返回一个承诺。如果您阅读有关 Promise 的内容,您会发现有一些方法可以解决您的问题。 这是一个:

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);
  });
}

那么你就可以使用这个功能了:

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

  // `allow` now could be used here
  console.log(allow);
});

【讨论】:

  • 谢谢,但它没有用,我使用 fflip,它返回错误值,我希望能够在 criteria 的 fflip 函数内进行查询:c
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-16
  • 2016-04-25
  • 2019-09-06
  • 2017-05-26
  • 2016-03-02
  • 1970-01-01
  • 2017-02-17
相关资源
最近更新 更多