[英]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. 有关jQuery延迟对象的Pluralsight教程提供了这个示例,我在其中添加了一些
console.log
。 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!" 它异步地将三个html文件加载到三个div中,并成功显示在屏幕上“工作!”-但是
console.log
正在打印“成功!”。 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. 如果将
console.log
放在代码的when
部分中,那也是一样—它打印内容在实际加载到屏幕上之前已完成加载。
So why does processing on the DOM occur as expected (on success), but console.log
messages are printed earlier than success? 那么,为什么对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!');
});
});
In your loadSection
function, change 在您的
loadSection
函数中,更改
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 这应该返回一个承诺,该承诺将在
.html(result)
完成时解析,而不是在$.get
完成时解析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.