jquery - 延迟对象 catch() 方法链接
问题描述
我是 jQuery 的新手。我目前正在学习 jQuery 中的延迟对象。我在运行我的 jQuery 代码时遇到问题。
问题是当我的延迟对象以已解决状态返回时,它正在调用被调用successCallBack
的函数,done()
但在该函数之后定义的函数catch()
也被执行。
为什么会这样?
感谢您的任何建议。
$(document).ready(function () {
$('#btnLoadImage').click(function () {
var dfd = getImages(); // Returns Deferred object
dfd.always(alwaysCallBack('Ajax is Called'));
dfd.progress(progressCallback);
dfd.done(successCallBack);
dfd.catch(errorCallback).then(function () {
console.log(dfd.state());
setTimeout(function () {
$('.gallery').empty();
$('.gallery').append('<center><input type="button" id="btnTryAgain" style="width:200px" class="btn btn-primary" value="Try Again" /></center>');
}, 3000);
});
});
$('.gallery').on('click', '#btnTryAgain', function () {
console.log('Hello');
$('.gallery').empty();
$('#btnLoadImage').click();
})
function getImages() {
var dfd = new $.Deferred();
$.ajax({
method: 'GET',
url: 'https://api.pexels.com/v1/search?query=car',
dataType : 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', API_KEY);
xhr.setRequestHeader('Accept','application/json');
},
success: function (data) {
dfd.notify('Loading...');
setTimeout(function () { dfd.resolve(data) }, 3000);
},
error: function (error) {
dfd.notify('Loading...');
setTimeout(function () { dfd.reject('Response Rejected.') }, 3000);
}
});
return dfd.promise();
}
function successCallBack(data) {
$('.gallery').empty();
data.photos.forEach(photo => {
const item = document.createElement('div');
item.classList.add('item');
item.innerHTML = `<img src="${photo.src.medium}">`;
$('.gallery').append(item);
});
}
function errorCallback(errorMessage) {
$('.gallery').empty();
$('.gallery').append('<p><h1 style="color:red">' + errorMessage + '</h1></p>');
}
function progressCallback(progressMessage) {
$('.gallery').empty();
$('.gallery').append('<p><h1>' + progressMessage + '</h1></p>');
}
function alwaysCallBack(message) {
console.log(message);
}
});
延期解决:
调用后定义的函数catch()
。
解决方案
推荐阅读
- docker - 如何在 minikube 中创建多个集群
- iphone-privateapi - AppLaunchStats:PrivateFrameworks/AppLaunchStats.framework 可用于启动应用程序?
- regex - 正则表达式:提取由特定单词分隔的单词
- flutter - 如何使用不迁移到空安全的包进行构建?
- c# - MciSendString 别名重用
- .net - 更新到引导程序 5 MVC 后在 WebGrease.dll 中引发异常
- php - php ajax一次又一次地获取相同的文件html
- gradle - Gradle 7 迁移:无法应用 PublishPlugin(maven-publish):当项目已经评估时无法运行 afterEvaluate
- android - Flutter:android不允许应用在外部存储中创建新文件夹来保存文件?
- maven - Apache flink force-shading 依赖的源码