简体   繁体   中英

Jquery's callback execution order with success and when

having the following code, whats the order of execution of the callback functions?

According to my tests showData() is always executed last, but these are pretty light operations, if i had more complex operations, does the $.when(...).then(callback) always wait for the success callbacks to finish before executing? here is a fiddle for easier testing.

function showData() {
      console.log("show data after when");
    //can i be sure that method1 success and method2 success have finished?
}

function method1() {
    return $.ajax('https://jsfiddle.net/echo/jsonp/', {
        dataType: 'jsonp',
        success: function(){ console.log("method 1 success")}
    });
}

function method2() {
    return $.ajax('https://jsfiddle.net/echo/jsonp/', {
        dataType: 'jsonp',
        success: function(){ console.log("method 2 success")}
    });
}

$.when(method1(), method2()).then(showData);

According to this information from jquery docs

Description: Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events.

$.when() provides a way to execute your callback function in that case showData() function.

Yep, that will work as you predicted.

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