Why can't the data in the Koa callback function respond to the front end? If you don't use await

problem description

you can use await, but why not use traditional callbacks?

related codes

router.get("/getArticles", async (ctx) => {
    let { sizes, pageNum } = ctx.query
    
    sizes = Number(sizes)
    pageNum = Number(pageNum)

    const skip = (pageNum - 1) * sizes

    const data = await Article.find({}).skip(skip).limit(sizes)
    
    //
    ctx.body = {
        code: 0,
        data
    }
})

what result do you expect? What is the error message actually seen?

if callback is used, how can I correct it without await?

Mar.08,2022

because the callback in your previous code is executed asynchronously, which is itself Article.find ({}) .skip (skip) .limit (sizes) .exec (.). The call will flash, and the koa2 middleware pipeline will be executed instantly and respond to the front end. By the time your data query comes back and the callback is called, ctx will be meaningless.

Menu