简体   繁体   中英

Why I can't use ctx.body in the callback of save()?

I can use ctx.body in find() 's callback:

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();
});

But I can't use it in save() 's callback:

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();
});

The code runs successfully,just the ctx.body doesn't work, why?

OK,I changed my code to this:

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();
});

Then the ctx.body worked.

And I'll never write ctx.body in the callback, it's so queasily...

But I still don't know why the ctx.body can work in the find() 's callback but not in the save() s?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM