[英]console.log processed before deferred object returned to .done
有关jQuery延迟对象的Pluralsight教程提供了这个示例,我在其中添加了一些console.log
。 它异步地将三个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!');
});
});
在您的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
完成时解析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.