0

I have a question, how can i get a variable value (in my example array variable) outside of a callback function? Here is my code!

var Db = require("../database/databaseInit");
var array = [];

class DBManager{
getUsers() {
        Db.find({}, function (err, users) {

            users.forEach(function (element) {  
            array.push(element.username);
            console.log(array) //here prints the users that i have in DB file
            });
        });
         console.log(array) // but here prints []
         return array;`enter code here`
    }
}
Andrei
  • 11
  • 3

2 Answers2

0

The second console.log in your code actually gets called first, before the database operation is complete, hence it is empty.

Change getUsers to accept a callback and invoke that once the database operation is complete and arrays is populated.

class DBManager {
    getUsers(done) {
        Db.find({}, function (err, users) {
            var array = [];
            users.forEach(function (element) {  
                array.push(element.username);
                console.log(array) //here prints the users that i have in DB file
            });
            done(array);
        });
    }
}

new DBManager().getUsers(function (array) {
    console.log(array);
});

You should read about how asynchronous operations work in JavaScript. At the moment you are treating them as synchronous.

Community
  • 1
  • 1
sdgluck
  • 24,894
  • 8
  • 75
  • 90
  • Thank you for your solution. It worked! Yes I am new on javascript, need to tread them asyn ! – Andrei Mar 01 '17 at 12:24
0

getUsers is defined by passing a callback as a parameter. When calling getUsers, you try to console.log array and to return it, however, your problem is that console.log and return are actually executed before the callback is being called.

Flow:

  • getUsers is called
  • console.log and return
  • the request is completed and the callback is executed

You have a code somewhere which calls getUsers and expects its output to be a valid array. You need to write a function with the part starting from using the result of getUsers and take that part out from the code where it was. The new function should have a parameter for array and you should call the function with array as the last operation of your callback. You might need to check the length of array whether it matches the expected length before calling your function.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175