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('' + id + '&password=' + password,
                  function (data, status) {
                      if (status === 'success') {
                        catalogue = $.parseJSON(data);
                        if (catalogue.status === "error") {
                        } else {
                            if (callback) callback(true);
                      } else {
                        alert("Error connecting to API:" + status);
          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;

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() {
  }, 1000);



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'.