Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 525
Roozbeh G Avatar asked Dec 24 '22 08:12

Roozbeh G


2 Answers

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/

like image 171
Jonathan.Brink Avatar answered Jan 25 '23 23:01

Jonathan.Brink


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

like image 41
humanityANDpeace Avatar answered Jan 26 '23 00:01

humanityANDpeace