Nie Selam
Nie Selam

Reputation: 1451

wait for sequelizer findOne to check database before returning a value

I am not sure what I am doing wrong. But i have this little function:

tripStatus (id) {



db.Trip.findOne({ attributes:['status'], where: {id: id} }).then(trip => {
    // trip will be null if not found else contains information about the trip

    if(trip!=null){

        console.log('found ', trip.dataValues['status']);
        return trip.dataValues['status'];


    }
    else{
        return -1;
    }
  }).catch(err=>{

      return -1;
  })


}

now I call it like this:

  var status=TripFunctions.tripStatus(1)
  //console out puts now in order of display on the console
  console.log(status) // gives undefined. FIrst out put
  'SELECT status from Trip WHERE id=1'
  "Found status 3"

It is returning value immediately it seems.

Upvotes: 0

Views: 1125

Answers (1)

doublesharp
doublesharp

Reputation: 27667

You are returning the values inside of the Promise created by Sequelize but not returning that promise from your function. Resolve the values in the promise and return to so that you can wait for the results.

You should also use the Instance.getDataValue() function instead of accessing them directly, or better use use raw: true to not construct an object at all if you just need the status - it will return a plain JSON object. Probably using Model.findById() too.

tripStatus (id) {
  // return the promise
  return db.Trip.findById(id, {
    attributes:['status'],
    raw: true,
  })
  .then(trip => {
    // trip will be null if not found else contains information about the trip
    return Promise.resolve(trip ? trip.status : -1);
  })
  .catch(err => {
    return Promise.resolve(-1);
  });
}

Call it like so using a Promise

TripFunctions.tripStatus(1).then((status) => {
  // the status is available in the promise resolution
  if (status !== -1) {
    // do something
  }
});

It would be more concise to write this using async/await.

async function tripStatus (id) {
  const trip = await db.Trip.findById(id, {
    attributes:['status'], raw: true});
  return trip ? trip.status : -1;
}

Then you can call it with async/await.

const status = await TripFunctions.tripStatus(1);
if (status !== -1) {
  // do something
}

Upvotes: 1

Related Questions