0

This program outprints first 0 then 189. I know that its due to javascripts executing this asynchronously. What would be the correct way to make both logs output 189? Without getting into callback hell?

roaming = [];

connection.query("SELECT land FROM roaming", function (err, res) {
    if (err) {
        console.log("Error: " + err);
    } else {
        res.forEach(function(entry){
            roaming.push(entry.land);   
        });
        console.log(roaming.length);
    }
});
console.log(roaming.length);
mrfr
  • 1,724
  • 2
  • 23
  • 44
  • You can't get them the same. `connection.query()` is an asynchronous function. Your second `console.log()` runs immediately, it can't wait for it to complete. That's why async functions have callbacks. – Barmar May 11 '17 at 10:20

2 Answers2

2

I would use async/await

async function asyncStuff() {  
  //async stuff  
}

await asyncStuff();
1

In Javascript, you can use "callback function". It means a function can be passed as a parameter. Example:

function hello (val1, callback) { 
   console.log(val1);
   callback();
 }
function callback() {
 //do something.
}

So you can pass callback function like hello ('a', callback);

Tran Ho
  • 1,442
  • 9
  • 15
  • This seems like a workaround, i might be at fault here. But is this considerd the standard way of doing this? What if I have a function that needs value of two SQL calls. Then I will need to ad a callback in my callback? – mrfr May 11 '17 at 09:38