0

I have a function that returns a certain json after it executes the query. but that json is coming as default, which i set, but i want the updated values from db.

Code :-

function addPet(pet) {
    var body = {
        msg : "",
        insertId : null
    };
    console.log(pet.pet_type);
    if(pet.pet_type){
        mysql.mySqlConnection.query("insert into master_pet(pet_type) values(?)",[pet.pet_type], (err,rows,fields) => {
            if(err){
                console.log("Query Error :- " + err ); 
                body.msg = "Error While Inserting";
                body.insertId = null;
                console.log("reached here");
                return body;
            }
            else{
                console.log("Inserted" + pet.pet_type);
                console.log(rows.insertId);
                body.msg = "Inserted Successfully";
                body.insertId = rows.insertId;                   
                console.log("reached here");
                return body;
            }
        });
        return body;
    }
}

Calling Method :-

   routes.post('/setPet',(req,res) => {
        var pet = req.body;
        var body = petmodel.addPet(pet);
        res.setHeader('Content-Type', 'application/json');
        res.json(body);
    });

in here on the client, the json which I am receiving is default one. Please help.

TIA

Archit Goel
  • 57
  • 1
  • 6
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Wiktor Zychla Dec 31 '18 at 12:52

1 Answers1

0
function addPet(pet, callback) {
    var body = {
        msg : "",
        insertId : null
    };
    console.log(pet.pet_type);
    if(pet.pet_type){
        mysql.mySqlConnection.query("insert into master_pet(pet_type) values(?)",[pet.pet_type], (err,rows,fields) => {
            if(err){
                console.log("Query Error :- " + err ); 
                body.msg = "Error While Inserting";
                body.insertId = null;
                console.log("reached here");
            }
            else{
                console.log("Inserted" + pet.pet_type);
                console.log(rows.insertId);
                body.msg = "Inserted Successfully";
                body.insertId = rows.insertId;                   
                console.log("reached here");
            }
            return callback(body);
        });
    }
}

--

routes.post('/setPet',(req,res) => {
        var pet = req.body;
        petmodel.addPet(pet, (body) => {
           res.setHeader('Content-Type', 'application/json');
           return res.json(body);
        });

    });
Roi
  • 983
  • 9
  • 17