为什么我不能在save()的回调中使用ctx.body?

问题描述 投票:0回答:1

我可以在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不起作用,为什么?

javascript node.js mongoose koa
1个回答
0
投票

确定,我将代码更改为此:

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()的回调中工作?

© www.soinside.com 2019 - 2024. All rights reserved.