Javascript 如何嵌套jQuery.when调用回调?
我有一个加载一个节的函数Javascript 如何嵌套jQuery.when调用回调?,javascript,ajax,jquery,asynchronous,Javascript,Ajax,Jquery,Asynchronous,我有一个加载一个节的函数 function loadSection(sectionId, onLoaded) { $.when( loadTemplate(sectionId), // etc ) .then(function () { // removed for brevity } } 在loadTemplate功能中,我淡出当前模板,淡出后加载新模板 function loadTemplate(section
function loadSection(sectionId, onLoaded) {
$.when(
loadTemplate(sectionId),
// etc
)
.then(function () {
// removed for brevity
}
}
在loadTemplate
功能中,我淡出当前模板,淡出后加载新模板
function loadTemplate(sectionId) {
// Fade out current template.
return $content.fadeOut(function () {
// After fade out, load new template via ajax.
$.ajax({
url: settings.apiUrl + 'GetSectionTemplate',
data: { sectionId: sectionId },
type: 'post',
success: function (template) {
// Add new content and fade in new template.
$content
.html(template)
.fadeIn();
}
});
});
}
问题是,
$.when
仅等待淡出功能完成后再继续。我需要它等待淡出和ajax调用完成,但我需要ajax调用仅在淡出完成后执行。尝试使ajax调用同步:
$.ajax({
async: false,
url: settings.apiUrl + 'GetSectionTemplate',
...
...
只需使用
数组
将Promise对象推入并返回。像
function loadTemplate(sectionId) {
var promises = [ ];
// Fade out current template.
promises.push($content.fadeOut());
promises.push($.ajax({
url: settings.apiUrl + 'GetSectionTemplate',
data: { sectionId: sectionId },
type: 'post',
success: function (template) {
// Add new content and fade in new template.
$content
.html(template)
.fadeIn();
}
}));
return promises;
}
然后像这样称呼它
$.when.apply( null,
loadTemplate(sectionId)
).then(function() {
});
如果您需要更多地控制承诺对象解析的顺序,或者希望截取/过滤结果,也可以使用
.pipe()
对承诺进行一定程度的解析。创建一个延迟对象,返回它,然后在ajax完成时解析它:
function loadTemplate(sectionId) {
var deferred = $.Deferred();
$content.fadeOut(function () {
$.ajax({
url: settings.apiUrl + 'GetSectionTemplate',
data: { sectionId: sectionId },
type: 'post',
success: function (template) {
$content.html(template).fadeIn();
deferred.resolve();
}
});
});
return deferred;
}
如果
返回$.ajax({})代码>?@ianpgall从淡出回调函数返回的所有返回值。我试过了。它不能修复任何东西。你的loadTemplate函数需要参与延迟/承诺世界。它可能是一个“修复”,通过强制淡出回调为同步操作,但肯定有更好的方法。@Fabricio Matté是的,它属于“丑陋的黑客”类别,但有时这是唯一的方法,没有说明这种情况。这很可能是可用的最糟糕的解决方案。,//etc
在加载模板(sectionId)
之后的作用是什么?您已经提供了一个包含所有参数的数组。当时,否?@fabriciomatté:复制和粘贴失败。这实际上不起作用,因为在淡出完成之前,ajax调用不会添加到数组中。与此同时,该数组已被提交给$.when.apply()
。我将尝试组合一个JSFIDLE来显示问题。@AlexFord:然后将.ajax()
移动到与.fadeOut
相同的级别。“应该这样做。@阿列克斯福德这把小提琴可以帮你省去麻烦: