DEV Community

SrinjaTheNinja
SrinjaTheNinja

Posted on

why i get response before request status in command prompt, although i have got right output in postman?

cmd ss
cmd ss2
postman

in cmd ss2, why console.log r shown before request GET /api/categories 200 334.691 ms - 1078??

here, i want to get all categories, my code runs good but i cannot understand command prompt part??

category controller-->

exports.list=(req,res)=>{
//console.log(req);
Category.find().exec((err,data)=>{
if(err)
{
return res.status(400).json({
error: errorHandler(err)
})
}
let r=res.json(data);
console.log(r);
return r;
})
}

category route-->

`const express=require('express')
const router=express.Router()//new router object
const{ create,categoryById,read,update,remove,list }=require('../controllers/category');
const{ requireSignin, isAuth, isAdmin }=require('../controllers/auth');
//const {userSignupValidator}= require('../validator');
const{ userById }=require('../controllers/user');

router.get("/category/:categoryId",read);

router.post("/category/create/:userId",requireSignin,isAuth,isAdmin,create);//sir told requireSignin,isAuth,isAdmin, as mw and create as only method

router.put("/category/:categoryId/:userId",requireSignin,isAuth,isAdmin,update);

router.delete("/category/:categoryId/:userId",requireSignin,isAuth,isAdmin,remove);

router.get("/categories",list);

router.param("categoryId",categoryById);

router.param("userId",userById);
module.exports=router;`

Latest comments (2)

Collapse
 
srinja333 profile image
SrinjaTheNinja

Thanks

Collapse
 
zoppatorsk profile image
Zoppatorsk • Edited

It's hard to see what is what in your code... should use 3 backticks with js after and then end with 3 backticks

Like below

exports.list = (req, res) => {
    //console.log(req);
    Category.find().exec((err, data) => {
        if (err) {
            return res.status(400).json({
                error: errorHandler(err),
            });
        }
        let r = res.json(data);
        console.log(r);
        return r;
    });
};

Enter fullscreen mode Exit fullscreen mode

If the console.log r does not have what u expect then probably

let r=res.json(data);
Enter fullscreen mode Exit fullscreen mode

Is async and execution will not wait for that before u console.log

But at same time I do not understand why u do the res.json(data).. this will stringify the data and send it to client... and try to store it in r (does res.json() even return anything??) that u then return..

And yeah, what u log is the res-object..

The code just don't make much sense to me..