0

I'm new to JavaScript and NodeJS, and I need to solve this issue quickly.

      connection(getSQL2)
    .then((table)=> {
        table.forEach(row=> {
            let obj = {
                countryid: row.IdPais,
                country: row.NombrePais
            };
            data.push(obj);
          });

        });

console.log(obj);

When I try to display the object using console.log, I get undefined, which seems pretty obvious. But what would be an easy way to get it to display the Object 'obj' that was created above?

UPDATE: Just to clarify, console.log is used here only as an example. I need to access the object from outside that function however I can.

Thanks in advance!

  • Move the console.log call inside the callback, where you defined `obj`. – Felix Kling Dec 18 '16 at 06:40
  • I just put the console.log outside to make it clear that I need to access the object from outside. I need to get some data from that object within some other function. As if it was a global variable. Thanks anyway. – David Martínez Dec 18 '16 at 06:47
  • try consoling `data`, it will be defined outside – anwerj Dec 18 '16 at 07:25
  • @anwerjunaid How so? – David Martínez Dec 18 '16 at 07:39
  • *"I need to access the object from outside that function however I can."* And that's usually a mistake. Why do you think you need to do that? Please provide a complete example. Please read [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/q/23667086/218196). – Felix Kling Dec 18 '16 at 08:39
  • I'm working on a project where we need to dynamically migrate an entire MsSQL db and put the contents of each table into a different MongoDB collection. – David Martínez Dec 18 '16 at 08:49
  • In this particular case I need to merge two SQL tables into a single Mongo collection. I know how to get fields from an object. But I can't access it because it's not a global variable. – David Martínez Dec 18 '16 at 08:50
  • *"I can't access it because it's not a global variable."* You don't need global variables. Put the code that needs access to the data into a function. Call the function from the callback and pass the data to it. – Felix Kling Dec 19 '16 at 07:35

3 Answers3

0

Two things going on here.

1) You're using a promise and promises asynchronously resolve. Good rule of thumb is any code that ends with .then(...) is going to be a promise. What that means is that code underneath it can execute before the promise is finished and if it reads those values before the promise has finished resolving they will be read as undefined.

2) You use the let keyword to define your variable which means it will only be defined in the scope:

row => {
            let obj = {
                countryid: row.IdPais,
                country: row.NombrePais
            };
            data.push(obj);

            // Show the object where it is defined
            console.log(obj);
          }
Mike
  • 3,830
  • 2
  • 16
  • 23
0

You need to do this:-

 async database()
{

      try {
            const table= await connection(getSQL2);
            if (table!== null)
            {
             table.forEach(row=> {
              let obj = {
                          countryid: row.IdPais,
                          country: row.NombrePais
                        }; 
             console.log('This will resolve the promise',obj);
            }
            else 
            {
             //anything needed 
            }
          } 
            catch (error) 
           {
                       // Error retrieving data
           }
}

async and await are the keywords used in parallel. await keyword will not allow the control to go down until data is fetched.

Ravi Shankar Bharti
  • 8,922
  • 5
  • 28
  • 52
Codesingh
  • 3,316
  • 1
  • 11
  • 18
0

you can create a global variable, and assign the value to that variable inside the that function.

Then, you will be able to access the variable obj outside the function also.

var temp;//declare a global variable here.
connection(getSQL2)
.then((table)=> {
    table.forEach(row=> {
        let obj = {
            countryid: row.IdPais,
            country: row.NombrePais
        };
        data.push(obj);
        temp = obj;//assign value to global variable here
      });

    });

console.log(temp);//you can access the 'obj' using temp

Hope this helps you.

Ravi Shankar Bharti
  • 8,922
  • 5
  • 28
  • 52