Wednesday, 26 April 2017

node.js Function executes without waiting for return [duplicate]

This question already has an answer here:

I am new to node.js and I am writing a script that will insert a value into my DB and then return the whole set back to the user.

The code is as follows:

app.post('/insert', function(request, response) {
    var connection = mySequel.createConnection(ConnectionParams);
    connection.connect();
    var UserName = request.body.UserName;
    //     insert into userrecords values ("123456",DEFAULT,DEFAULT,DEFAULT,10);
    var InsertQuery = "insert into userrecords values (" + UserName + ",DEFAULT,DEFAULT,DEFAULT,-10);";
    connection.query(InsertQuery, function(error, result, fields) {
        if (error) {
            response.send("error");
            console.log(error);
            throw error;
        } else {
            // response.send("success");
            var s = result.insertId;
            var resultFromFn = getLastInsertedRow(s, response);
            console.log("Message from insert is " + resultFromFn);
            response.send(resultFromFn);
        }
    });
    connection.end();
});

//This function returns the last inserted row
function getLastInsertedRow(n, response) {
    var connection = mySequel.createConnection(ConnectionParams);
    connection.connect();
    var buery = "select * from userrecords where Unique_ID = " + n + ";";
    connection.query(buery, function(error, result, fields) {
        if (error) {
            response.send(error);
            console.log(error);
            throw err;
        } else {
            var JSONResult = [];
            JSONResult = JSON.stringify(result);
            console.log("from the function" + JSONResult);
            response.send(JSONResult);

        }
    });
    connection.end();
    // select * from userrecords order by TimeStamp1 DESC;
}

The result got from the console is

Message from insert is undefined 2017-04-26T10:13:50.235184+00:00 app[web.1]: from the function[{"Emp_ID":"123","Unique_ID":302,"TimeStamp1":"2017-04-26T10:13:50.000Z","TimeStamp2":"0000-00-00 00:00:00","Duration":-10}]

It can seen from the log that the response.send() is executed before the function returns the original value. What can be dont so that this code produces the desired output? I want the whole JSON to be sent back to the user.



via Tyson

No comments:

Post a Comment