Kevin Kevin - 2 months ago 21
Node.js Question

How to wait on sequelize executing a findOne

I've got a route using Sequelize.js

app.get('/api/users/:username', (req, res) => {
const foundUser = getUserByUsername(req.params.username);
console.log(`foundUser = ${foundUser}`);
return res.send(foundUser);
});


the getUserByUsername function is as follows

const getUserByUsername = username => {
Viewer.findOne({
where: {username}
}).then(response => {
console.log(response.dataValues);//the object with the data I need
return response.dataValues;
});
};


I hoped on getting the object in my const foundUser in my route, but it seems I need to wait until the findOne has been executed, because in my console I can see that the log of foundUser (which is undefined then) is executed before the function getUserByUsername

foundUser = undefined
Executing (default): SELECT `id`, `username`, `instakluiten`, `role`, `createdAt`, `updatedAt` FROM `viewers` AS `viewer` WHERE `viewer`.`username` = 'instak' LIMIT 1;
{ id: 19,
username: 'instak',
instakluiten: 18550,
role: 'moderators',
createdAt: 2016-10-02T16:27:44.000Z,
updatedAt: 2016-10-09T10:17:40.000Z }


How can I make sure that my foundUser will be updated with the data √°fter the user has been found?

Answer

You have to return the promise that Sequelize creates and then wait for it to resolve. So the getUserByUsername becomes:

const getUserByUsername = username => {
  return Viewer.findOne({
    where: {username}
  }).then(response => {
    console.log(response.dataValues);//the object with the data I need
    return response.dataValues;
  });
};

and in the route:

app.get('/api/users/:username', (req, res) => {
  getUserByUsername(req.params.username).then(foundUser => {
    res.send(foundUser);
  });
});

This is because you need to keep the chain of promises. If you forget to return it, the function returns undefined end even if the promise is finallly resolved, the value it resolves to never gets up back in the chain.