0

I have a javascript function foo. I want bar to be called when foo is complete. I have tried it as a callback. It does not work. Bar is called while foo is still executing the $.get (which starts a very long python routine on the server).

  function foo(callback){
    $.get(
        url="/myurl",
        data={key:($(this).attr('data-button'))}, 
        function(returndata) {
            var array = eval(returndata);
            drawTable(array);
      });

      callback();
  }

foo(bar);

This however works. I am confused as to why...

  function foo(callback){
    $.get(
        url="/myurl",
        data={key:($(this).attr('data-button'))}, 
        function(returndata) {
            var array = eval(returndata);
            drawTable(array);
            callback();
      });

  }

foo(bar);

DG1
  • 171
  • 1
  • 8
  • http://blog.slaks.net/2015-01-04/async-method-patterns/ – SLaks Feb 03 '15 at 18:06
  • Callback happens when the call is returned: http://stackoverflow.com/a/4560233/14104 The first one you treat it like it is a synchronous call, second one is treated correctly for an asynchronous call. – epascarello Feb 03 '15 at 18:08
  • So, in the first example, I call $.get, which starts running, and then because it was called bar is called (even through $.get is not complete)... in the second example, $.get has a callback to bar when it is done, so it works. Do I understand that correctly? – DG1 Feb 03 '15 at 18:13

2 Answers2

1

this is because $.get is asynchronous. from the docs ...

This is a shorthand Ajax function, which is equivalent to:
$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

you can think of it being run in a separate thread. so bar() wont act as a callback . but in your 2nd example "function(returndata)" is the callback function for $.get hence giving bar() inside will do the job as now bar() will only be called after $.get is finished.

Nithin
  • 5,470
  • 37
  • 44
0

it's working in second case as 'bar()' is being called once the response comes .Now coming back to callback, Simple concept of writing callback is below :

function func1(callback) {
  alert('func1');
  callback();
}

function func2() {
  alert('func2');
}

func1(func2);

so in your case, ideally this should work :

 function foo(callback) {
   $.get(
     url = "/myurl",
     data = {
       key: ($(this).attr('data-button'))
     },
     function(returndata) {
       var array = eval(returndata);
       drawTable(array);
       callback.call();
     });
 }

 function bar() {
   //todo

 }

 foo(bar);
invinciblejai
  • 1,103
  • 1
  • 8
  • 15