我有一条使用Sequelize.js的路线

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


getUserByUsername函数如下

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


我希望在我的路由中将对象保存在我的const foundUser中,但是似乎我需要等到findOne被执行,因为在我的控制台中,我可以看到foundUser的日志(当时是未定义的)在执行之前函数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 }


如何确定我的foundUser将使用已找到用户的数据进行更新?

最佳答案

您必须返回Sequelize创建的承诺,然后等待其解决。因此getUserByUsername变为:

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


并在路线中:

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


这是因为您需要遵守承诺链。如果您忘记返回它,即使最终解决了承诺,函数也会返回undefined end,它所解析的值永远不会回到链中。

10-02 16:41