【问题标题】:Sequelize query returns Promise. How to wait for query to return result?Sequelize 查询返回 Promise。如何等待查询返回结果?
【发布时间】:2019-04-16 23:58:46
【问题描述】:

我有两个模型与User 属于Status 关系。我正在尝试跟踪对User 记录中的status 列所做的更改。在我的钩子里,我有:

afterUpdate: (instance, options) => {
  if (instance.dataValues.statusId !== instance._previousDataValues.statusId){
    const Track = {
      new_status: sequelize.models.Status.findById(instance.dataValues.statusId).then(status => {
        console.log('1._____');
        console.log(status.dataValues.name);
        return status.dataValues.name;
      })
    }
    console.log('2.____');
    console.log(Track.new_status);
  } else{
    console.log('Status is not changed');
  }
}

输出:

2.____
Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }
Executing (default): SELECT "id", "name", "detail", "createdAt", "updatedAt" FROM "Statuses" AS "Status" WHERE "Status"."id" = 18;
1._____
Cancelled

我在console.log(Track.new_status) 看到查询尚未完成,在console.log(status.dataValues.name) 它正确地返回了状态名称。如何让它等到它完成查询?

【问题讨论】:

标签: node.js orm sequelize.js sequelize-cli


【解决方案1】:

使用async/await

async function getTrack(trackID) {
  const track = await Track.findByPk(trackID);
  console.log('track', track);
}

使用承诺:

function getTrack(trackID) {
  const track = Track.findByPk(trackID)
  .then((track) => {
    console.log('track', track);
  });
}

【讨论】:

  • 谢谢,根据CertainPerformance 的建议,我使用了 await 但没有在这里发帖。它与您的解决方案相同。所以,我会标记它已解决。谢谢你的回答:)
猜你喜欢
  • 2012-10-28
  • 2017-11-06
  • 1970-01-01
  • 2013-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多