我正在尝试实现一个加载更多的ajax函数。但是,无论何时单击该按钮,它都会在解析延迟对象之前在then()内运行该函数。我必须使用setTimeout才能使它工作。我不认为这是一种正确的方法,因为它使then()完全没有意义?任何人都可以看一下发生了什么事吗?谢谢。
$(document).on('click', '.c-button--lg', function() {
var appendHTML = function () {
var $dfd = $.Deferred();
$.get(nextLink, function(html) {
$pillarContainer.append(html);
console.log(0);
$dfd.resolve();
});
return $dfd.promise();
};
appendHTML().then(function(){
console.log(1); //This is running before console.log(0);
});
});
因为你定义了appendHTML
,但是在你的代码示例中调用appendData()
,你的代码中的appendData()
实际上是做什么的并不清楚。
如果你的意思是appendHTML
和appendData
在你的问题中是相同的函数名,那么你可以大大简化你所拥有的这个并且还避免promise anti-pattern将现有的承诺包装在另一个不必要的承诺/延期中(并且还避免了你的错误)这样做是因为你没有适当的错误处理)。而且,它也不应该有您报告的问题。
这段代码只返回$.get()
已经返回的承诺,它使用该promise来处理结果,因此你一直使用promises(不将promises与自定义jQuery回调混合):
$(document).on('click', '.c-button--lg', function () {
// define $pillarContainer somewhere in here
function appendData() {
return $.get(nextLink).then(function(html) {
$pillarContainer.append(html);
console.log(0);
return html;
});
};
appendData().then(function () {
console.log(1); //This is running before console.log(0);
});
});