【问题标题】:Using Sequelize findOne returns before function is finished在函数完成之前使用 Sequelize findOne 返回
【发布时间】:2021-12-31 19:08:19
【问题描述】:

我正在使用带有 Sequelize 的 Koa 路由器。而且我使用了Sequelize init,其中模型的创建方式如下:

module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    static associate(models) {
      // Associations...
    }
  }
  User.init(
    {
      email: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      password: {
        type: DataTypes.STRING,
        allowNull: false,
      },
    },
    {
      sequelize,
      modelName: 'User',
      timestamps: false,
    }
  );
  return User;
};

而 koa-router 有:

router.get('/:id', UserController.get);

中间件有:

const db = require('../../../models/index');

module.exports = () => async (ctx, next) => {
  try {
    ctx.db = db;
    next();
  } catch (err) {
    console.error(err);
    ctx.status = 500;
  }
};

现在,我有以下代码:

UserController.get = async (ctx) => {
  try {
    const user = await ctx.db.User.findOne({
      where: { id: ctx.params.id });

    if (user) {
      ctx.body = user;
      ctx.status = 200;
    } else {
      ctx.status = 404;
    }
  } catch (error) {
    ctx.status = 500;
  }
};

当我单步调试调试器时,我看到当调试器移至 if (user) { 行时,此 GET 请求的响应返回为 404,即使函数 UserController.get 尚未完成。

任何想法为什么会这样?

【问题讨论】:

    标签: node.js sequelize.js koa koa-router


    【解决方案1】:
    const user = await ctx.db.User.findOne({
        where: { id: ctx.params.id }
    });
    

    你忘了一个右括号

    【讨论】:

    • 抱歉,是我复制粘贴代码时的拼写错误。但是,错误仍然存​​在。实际上,它从数据库中正确地检索了值,但是当它检索到值时,为时已晚,那时 http 响应已经发送。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    • 2020-09-26
    • 2015-02-17
    相关资源
    最近更新 更多