-2

I have a function getUserId() in that i have another function that return value from db. the result is placed in array arrUser. the array is printed in the function but not in another function. can any one give me the solution

function getUserId() {

    var arrUser = new Array();

    connection.query('SELECT iUserId,sFromEmailAddress FROM tblFromSenderList',function (err, results, fields) {
        if (err) {
            throw err;
        }

        if (results.length > 0) {
            for (var i = 0; i< results.length ;i++){
                var reader = results[i];
                // console.log(reader['sFromEmailAddress']+" == " + reader['iUserId']); //ADD string - 'ID: 1'
                arrUser[reader['sFromEmailAddress']] = reader['iUserId'];
            }

            console.log(arrUser); // prints value over here

            return arrUser;
        } 
    });

     console.log(arrUser);  // does not print value 
}
Lars de Bruijn
  • 1,430
  • 10
  • 15
max
  • 1
  • 4
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – VonD Apr 12 '16 at 09:36

1 Answers1

-1

That's normal. The query to the database is asynchronous, it means you are running this code console.log(arrUser); // does not print value before the query has completed. You can use a callback (in your case, it's useless, you can write your code in 1 single function...) :

function getUserId() {
  getArrayFromDatabase(function(err, result) {
    console.log(result);
  });
}


function getArrayFromDatabase(callback) {
  var arrUser = new Array();

  connection.query('SELECT iUserId,sFromEmailAddress FROM tblFromSenderList',function (err, results, fields) {
    if (err) {
      return callback(err, null);
    }

    if (results.length > 0) {
      for (var i = 0; i< results.length ;i++){
        var reader = results[i];
        arrUser[reader['sFromEmailAddress']] = reader['iUserId'];
      }

      console.log(arrUser); // prints value over here

      callback(null,arrUser);
    } 
 });
}
krakig
  • 1,515
  • 1
  • 19
  • 33
  • var objUser = new getUserId(); the object objUser must content the array arrUser – max Apr 12 '16 at 12:28