[英]Using Sequelize findOne returns before function is finished
I am using Koa router, with Sequelize.我正在使用带有 Sequelize 的 Koa 路由器。 And I have used Sequelize init, where the model is created as follows:
我使用了 Sequelize init,其中 model 创建如下:
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;
};
And the koa-router has:并且 koa-router 有:
router.get('/:id', UserController.get);
Middleware has:中间件有:
const db = require('../../../models/index');
module.exports = () => async (ctx, next) => {
try {
ctx.db = db;
next();
} catch (err) {
console.error(err);
ctx.status = 500;
}
};
Now, I have the following code:现在,我有以下代码:
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;
}
};
When I was stepping through debugger, I am seeing when the debugger moves to if (user) {
line the response from this GET request returns as 404, even though the function UserController.get
is not complete yet.当我单步调试调试器时,我看到调试器移动到
if (user) {
行时,此 GET 请求的响应返回为 404,即使 function UserController.get
尚未完成。
Any ideas why this could be?任何想法为什么会这样?
const user = await ctx.db.User.findOne({
where: { id: ctx.params.id }
});
You forgot a closing bracket你忘了一个右括号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.