【问题标题】:console.log processed before deferred object returned to .done在延迟对象返回 .done 之前处理的 console.log
【发布时间】:2017-01-12 14:33:31
【问题描述】:

关于 jQuery 延迟对象的 Pluralsight 教程有这个例子,我已经添加了一些 console.logs 到。它将三个 html 文件异步加载到三个 div 中,并在成功时打印到屏幕“工作!”--然而,console.log 正在打印“成功!”在处理实际完成之前到控制台。如果我将console.log 放在代码的when 部分中,同样的事情——它会在内容实际加载到屏幕上之前打印出内容已完成加载。

那么为什么 DOM 上的处理按预期进行(成功时),但 console.log 消息在成功之前打印?

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!');
    });
});

【问题讨论】:

  • 你为什么要在$.when() 的结果(延迟实例)上调用.promise()?您可以直接在该返回值上调用.done()
  • 这是因为对 DOM 的操作比 JavaScript 脚本慢得多
  • 你应该使用.then 而不是.promise().done()
  • 本教程从我们使用.then 开始,但后来您是否将其更改为.promise().done() 以防止延迟对象的状态被意外更改,我想是通过解析/拒绝。我还没走那么远。

标签: javascript jquery promise jquery-deferred


【解决方案1】:

在您的 loadSection 函数中,更改

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

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

这应该返回一个在 .html(result) 完成时解决的承诺,而不是在 $.get 完成时解决

【讨论】:

    猜你喜欢
    • 2015-05-01
    • 2012-09-05
    • 2018-04-12
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多