Home > database >  Compare data after sequelize asynchronous query
Compare data after sequelize asynchronous query

Time:02-20

I have this code :

VerificationKey.getCode = async (visitorData, visitorCode, res) => {
  console.log("Verif model visitorCode"   visitorCode);

  const data = visitorData;
  const testCode = visitorCode;
  const findVisitor = await VerificationKey.findOne({ where: { data } })

    .catch((err) => {
      console.log(err);
    })
    .then(() => {
      if (testCode == findVisitor.key) {
        res.status(200).json({ response: true });
      }
    });
};

What I need is to compare testCode and findVisitor.key values. If they are equal, I want to return a boolean to the front end.

But I can't write it like this because it is not possible to access findVisitor.key before initialization.

CodePudding user response:

I believe you have to change your code to use async/await syntax only - without then and catch:

VerificationKey.getCode = async (visitorData, visitorCode, res) => {
  console.log("Verif model visitorCode"   visitorCode);

  const data = visitorData;
  const testCode = visitorCode;

  try {
    const findVisitor = await VerificationKey.findOne({ where: { data } });
    
    if(!findVisitor) {
      res.status(404).json({ response: false });
    } else if(testCode == findVisitor.key) {
      res.status(200).json({ response: true });
    } else {
      res.status(403).json({ response: false });
    }
   } catch(err) {
    console.log(err);
   }
};

  • Related