-2

I am mew to node js, I have something like this,

    get_contacts(data, function(contacts) {
                if (contacts.length) {
                    var count = contacts.length;

                    for (var i = 0; i < count; i++) {
                        result = {
                            id: contacts[i].id,
                            name: contacts[i].name,
                            sent1: get_sent(data.userId, contacts[i].id, function(resp) {
                                result.sent = resp.count;
                            }),

                        }
                        result1[i] = result;
                    }

                    output = {
                        contacts: result1,
                    }
                } else {
                    output = {
                        error: "No Contacts.",
                    }
                }

                res.writeHead(200, {'content-type': 'text/html'});
                res.end(JSON.stringify(output));
            });

get_contacts is a callback function which will return contact list.result1 & result are objects. Now value for sent should come from a function get_sent, and get sent is like this

function get_sent(userId, contactId, callback) {
pool.getConnection(function(err, connection) {
    connection.query("my query here", function(err, rows) {
        connection.release();
        if (!err) {
            callback(rows);
        } else {
            console.log(err)
        }
    });
});

}

But im not getting any value since nodejs. since nodejs is async it is not waiting for the function to return value. I know, im doing it in wrong way. Please help

Niranjan N Raju
  • 12,047
  • 4
  • 22
  • 41
  • possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Aaron Dufour Sep 01 '15 at 13:31

1 Answers1

0

You need to use a callback. In simple words is a function that you'll execute after something happens. You should read more about that. You should get a book about javascript but you can start reading here for example.

About your case, you could solve it like this

//Asumming that you object `result` is global.
result = {
     id: contacts[i].id,
     name: contacts[i].name,
     sent: -1   //Some default value
 }

//Just to put the code into a function, you have to put it where you need
function constructObject (){

  get_sent(uId, cId, function(err, total){
    if(err){
      console.log("Something was wrong.", err);
    }
    result.sent = total;

    //Here you have your object completed
    console.log(result);
  });
}

//You need to use a callback
function get_sent(uId, cId, callback) {
pool.getConnection(function(err, connection) {
    //Note that I add an alias here
    connection.query("SELECT count(*) as total FROM table_name", function(err, rows) {
        connection.release();
            if (!err) {
                //I am returning the result of the query and a null error
                callback(err, rows[0].total);
            } else {
                console.log(err);
                //I am returning an error
                callback(err);
            }
        });
    });
}

//For example you could call this function here
constructObject();

And it depends of what are you doing exactly but Maybe you need a callback on your constructObject too.

Community
  • 1
  • 1
Gepser Hoil
  • 3,998
  • 4
  • 24
  • 34