![](/img/trans.png)
[英]Nodejs Webscraping function using Cheerio returns before finished
[英]Using Sequelize findOne returns before function is finished
我正在使用带有 Sequelize 的 Koa 路由器。 我使用了 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;
};
并且 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,即使 function UserController.get
尚未完成。
任何想法为什么会这样?
const user = await ctx.db.User.findOne({
where: { id: ctx.params.id }
});
你忘了一个右括号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.