I am trying to write some code in Javascript for first time, and I am guessing I dont get something conceptually!
The following code for me works fine :
var db = new alasql.Database("db");
db.exec('CREATE TABLE IF NOT EXISTS Myonetwo;');
var aaa = db.exec('select * into Myonetwo from json("http://localhost:8080/app1")',[],function(res){
db.exec('select * from Myonetwo;',[],function(bbb){
console.log(bbb.length);
});
});
But this one which is the same but not function inside function embedded, Does not work.
var db = new alasql.Database("db");
db.exec('CREATE TABLE IF NOT EXISTS Myonetwo;');
var aaa = db.exec('select * into Myonetwo from json("http://localhost:8080/app1")');
var bbb = db.exec('select * from Myonetwo;');
console.log(bbb.length);
Also Is getting result as a function defined as one of arguments something usuall for all Javascripts?
This is because the exec
function is asynchronous, so in your 2nd example the bbb
assignment line will happen prior to the aaa
assignment line finishing.
This is why exec
has a callback function as it's last parameter.
In your first code snippit the timeline of events will be something like:
In this case you know that the second exec call will happen after the first exec call.
Your second code snippit's timeline will be:
You can see that this will have a bearing on your logic.
Here is a good article to learn more about asynchrounous programming: https://blog.risingstack.com/asynchronous-javascript/
Yes Javascript does run lines of code in order. But is also contains asynchronous/deferred programming elements.
The concept can be looked up here https://developer.mozilla.org/en/docs/Web/JavaScript/EventLoop
It boils down to this:
console.log("a");
console.log("b"); // output will be a, b, c
console.log("c");
// output will be a, b, c
then again
console.log("a");
setTimeout(function(){
concole.log("b");
},0);
console.log("c");
//output will be a, c, b
The reason is that the code to print "b" appears both times before console.log("c")
but it is indeed not both times executed before. In the second case it is queued in the EventLoop via the window.setTimeout(function, timeout)
function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With