console.log 在延迟对象返回到 .done 之前处理
console.log processed before deferred object returned to .done
有关 jQuery 延迟对象的 Pluralsight 教程中有这个示例,我向其中添加了一些 console.log
。它将三个 html 文件异步加载到三个 div 中,并在成功时打印到屏幕 'Worked!'——但是,console.log
在处理之前将 "success!" 打印到控制台实际上完成。如果我将 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!');
});
});
在您的 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();
});
这应该 return 承诺在 .html(result)
完成时解决,而不是在 $.get
完成时解决
有关 jQuery 延迟对象的 Pluralsight 教程中有这个示例,我向其中添加了一些 console.log
。它将三个 html 文件异步加载到三个 div 中,并在成功时打印到屏幕 'Worked!'——但是,console.log
在处理之前将 "success!" 打印到控制台实际上完成。如果我将 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!');
});
});
在您的 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();
});
这应该 return 承诺在 .html(result)
完成时解决,而不是在 $.get
完成时解决