简体   繁体   中英

Sequelize query returns Promise. How to wait for query to return result?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM