简体   繁体   中英

console.log processed before deferred object returned to .done

The Pluralsight tutorial on jQuery deferred objects has this example that I've added some console.log s to. It's loading three html files into three divs asynchronously, and on success it prints to screen 'Worked!'--however, the console.log is printing "success!" to the console before the processing is actually complete. Same thing if I put console.log within the when portion of code--it prints that content is finished loading before it actually loads up on screen.

So why does processing on the DOM occur as expected (on success), but console.log messages are printed earlier than success?

var loadSection = function (options) {
    if (typeof options !== 'object')
    options = {
    };
    options.selector = options.selector || '';
    options.url = options.url || '';
    return $.get(options.url, function (result) {
        $(options.selector).html(result);
        console.log(options.url)
    }, 'html')
}
$('#Load').on('click', function () {
    $.when(loadSection({
        url: 'Content1.html',
        selector: '#Section1'
    }), loadSection({
        url: 'Content2.html',
        selector: '#Section2'
    }), loadSection({
        url: 'Content3.html',
        selector: '#Section3'
    })
    ).promise()
     .done(function (result) {
        $('#Messages').append('Worked!<br/>')
        console.log('success!');
    });
});

In your loadSection function, change

return $.get(options.url, function (result) {
    $(options.selector).html(result);
    console.log(options.url);
}, 'html')

to

return $.get(options.url, 'html')
.then(function (result) {
    console.log(options.url);
    return $(options.selector).html(result).promise();
});

this should return a promise that resolves when .html(result) is complete, rather than when $.get is complete

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