简体   繁体   中英

Run one function after another: callback issue

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/

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

You have to actually call callback .

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

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

lazy_1(lazy_2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM