1

I have two models with User belongsTo Status relationship. I am trying to track the changes made to the status column in the User record. In my hook I have:

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

Output:

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

I see that at console.log(Track.new_status) the querying is not yet completed and at console.log(status.dataValues.name) it rightly returns the status name. How to do I make it to wait until it complete the querying?

niaS
  • 323
  • 4
  • 18

1 Answers1

4

Using async/await:

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

Using Promises:

function getTrack(trackID) {
  const track = Track.findByPk(trackID)
  .then((track) => {
    console.log('track', track);
  });
}
doublesharp
  • 26,888
  • 6
  • 52
  • 73
  • Thanks, as per `CertainPerformance` suggestion, I used await but didn't post here. It is same as your solution. So, I'll mark it solved. Thank you for the answer :) – niaS Nov 15 '18 at 06:26