Why does my callback function always return to error instead of response in everycase

1260 views javascript
7

I'm learning node and I'm stuck resolving why callback is always returned to error

Here's my code

todo.createTask(req,(err,resp)=>{
if(err){
    res.status(400).send(err);
}else{
    res.status(200).send(resp);
}
});

var createTask(req,callBack) =>{
    var model = new models({
    .
    .
    .
    .
    });

    model.save().then((doc)=>{
        callBack(doc);
    }).catch((err)={
        callBack(err);
    })
}

I'm receiving successful msg from mongo with 400 status code that I used for error.

Please help me find what is that I'm doing wrong.

answered question

1 Answer

3

There are two cases where your callback is called:

callBack(doc);
callBack(err);

… in each of them, you pass one parameter. That is assigned to the first argument.

(err,resp)=>{

So in each case you assign something that is a true value to err and nothing to resp.

Your if(err){ then takes the true value from the first argument and behaves as you told it to.

If you want to avoid that, you need to pass a false value to err and the value you care about to resp.

posted this

Have an answer?

JD

Please login first before posting an answer.