0

I'm trying to understand why function lazy_2 doesn't run this way:

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

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

lazy_1(lazy_2);

? (Via Execute jquery function after another function completes.)

jQuery method works well:

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

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

$.when( lazy_1() ).done(function() {
    lazy_2();
});

http://jsfiddle.net/5LL69/

Community
  • 1
  • 1
A. Z.
  • 720
  • 1
  • 9
  • 27
  • possible duplicate of [Create a custom callback in JavaScript](http://stackoverflow.com/questions/2190850/create-a-custom-callback-in-javascript) – Felix Kling May 04 '14 at 14:53

2 Answers2

4

Because lazy_1() doesn't call it's callback - in fact nobody does. It needs to look like this for the callback to get called:

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

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

lazy_1(lazy_2);

Your second code block above is equivalent to:

lazy1();
lazy2();

because you're just asking jQuery $.when() to run one function and then another with no promises involved (all synchronous code).

jfriend00
  • 637,040
  • 88
  • 896
  • 906
2

You have to actually call callback.

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

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

lazy_1(lazy_2);
Paul Draper
  • 71,663
  • 43
  • 186
  • 262