I've encountered a situation where I had to set up the router using Express, and it was functioning correctly with the following code:
router.get('/',(req,res)=>{
queries.getAll().then(stickers=>{
res.json(stickers)
})
})
The queries.getAll()
function is responsible for executing the MySQL query to retrieve the necessary stickers data. However, when attempting to do something similar with Koa2, an issue arose:
router.get('/', async (ctx, next) => {
queries.getAll().then(stickers=>{
ctx.body = JSON.stringify(stickers)
})
}
From my understanding, it seemed necessary to include "await" before the query function, like so:
await queries.getAll().then(stickers=>{
ctx.body = JSON.stringify(stickers)
})
This suggests that in Koa2, one must wait for the MySQL query to complete before sending the results to the client. Otherwise, nothing will be sent. In contrast, it appears that Express automatically sends the result once the query finishes. What could be the reason behind this difference? Perhaps there are some essential concepts about Node.js that I am missing. Any assistance would be greatly appreciated.