Search code examples
javascriptalasql

Does Javascript run lines of code in order? and finish processing then move on?


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?


Solution

  • 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:

    • first exec call
    • some time passes...
    • first exec callback happens
    • second exec call executes
    • second exec callback happens

    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:

    • first exec call
    • second exec call
    • either first or second exec call finishes (non deterministic)
    • either first or second exec call finishes (non deterministic)

    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/