我可以在ctx.body
的回调中使用find()
:
router.post("/register/isNameUsed", async (ctx, next) => {
let username = ctx.request.body.username;
await userInfo.find({ username: username }, function(err, doc) {
if (err) {
console.log(err);
} else {
if (doc.length > 0) {
ctx.body = { isNameUsed: true };
} else {
ctx.body = { isNameUsed: false };
}
}
});
await next();
});
但是我不能在save()
的回调中使用它:
router.post("/register", async (ctx, next) => {
let username = ctx.request.body.name;
let password = ctx.request.body.password;
var ui = new userInfo({
username,
password
});
await ui.save(function(err, doc) {
if (err) {
console.log(err);
} else {
ctx.body = { registerSuccess: true };//It doesn't work
}
});
await next();
});
代码成功运行,只是ctx.body
不起作用,为什么?
确定,我将代码更改为此:
router.post("/register", async (ctx, next) => {
let username = ctx.request.body.name;
let password = ctx.request.body.password;
var ui = new userInfo({
username,
password
});
try {
let insertRes = await ui.save();
ctx.body = { registerSuccess: true };
} catch (error) {
ctx.body = { registerSuccess: false };
}
await next();
});
然后ctx.body
开始工作。
而且我永远也不会在回调中写ctx.body
,这很容易...
但是我仍然不知道为什么ctx.body
可以在find()
的回调中工作而不能在save()
的回调中工作?