Javascript function runs both routes


Still have problems with this. When I call this function it appears to return twice??? I get 'test2' in the console followed by 'test'. I also put the callback return value into the console and its false then true. The getwidget is only called once from this.nextwidget which is a button.

      getwidget = function (callback) {
          var id = get_name_value('salesperson');
          var password = 'password';
          if (id !== "") {
              $.get('http://somewhere.com?id=' + id + '&password=' + password,
                  function (data, status) {
                      console.log(status);
                      if (status === 'success') {
                        catalogue = $.parseJSON(data);
                        if (catalogue.status === "error") {
                            alert(catalogue.message);
                        } else {
                            console.log('test');
                            if (callback) callback(true);
                        }
                      } else {
                        alert("Error connecting to API:" + status);
                      }
                  });
          }
          console.log('test2');
          if (callback) callback(false);
      };

      this.nextwidget = function() {
          catindex = catindex + 1;

          getwidget(function(trigger) {
            if (!trigger && catindex > 0) {
                catindex = catindex - 1;
            }
            if (catindex === catlen - 1) {
                document.getElementById("nextwidget").disabled = true;
            }
            if (catindex !== 0) {
                document.getElementById("prevwidget").disabled = false;
            }
            console.log(catindex);
            console.log(trigger);
          });
      };

Javascript is asynchronous. $.get operation is asynchronous, because it is a call to the server.

It means that JS is not waiting till the end of this operation and just continuing excuting next block of code. So, according to your code, it shows 'test2' in a console, than executes callback with false parameter. And only when response from server received, it shows "test" in console and run callback with true parameter. (certainly, if request was successful, according to your snippet)

Here is simple jsfiddle for better understanding how it works. Simple async example

function asyncExample() {
  setTimeout(function() {
    console.log('test');
  }, 1000);

  console.log('test2')
}

asyncExample();

Because operation in timeout is delayed (like asynchronous), JS will not wait and just continue with next lines. So the result will be: 'test2' first and then 'test'.