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/