javascript - 使用 Jquery.ajax().then() 时无法 .catch() 出错
问题描述
我从 JQuery 中访问了许多 API,并缓存了每个 API 的结果,以便可以在页面中多次重复使用数据,以以不同的格式呈现一些仪表板小部件。
问题是,如果 API 返回 500 错误状态代码,我不想尝试绘制小部件,而是以友好的方式捕获错误。
但是,我无法弄清楚.catch
该功能是如何工作的JQuery.ajax()
。在阅读了 here、here、here、here和其他十几个之后,我到目前为止,但总是得到相同的控制台错误:
TypeError: LoadDataFromApi(...).then(...).catch 不是函数
我试图评论代码以解释我在每个阶段要做什么。请有人解释为什么整件事.catch
对我不起作用。
// Cache object to save API data for re-use
var requestCache = {};
// Get API data and save to cache
function LoadDataFromApi(apiUrl) {
if (!requestCache[apiUrl]) {
var result = $.ajax({
type: 'GET',
url: apiUrl,
dataType: "json",
statusCode: {
500: function (xhr) {
var err = JSON.parse(xhr.responseText);
console.log('Message:' + err.Message);
// throw err.Message; // removed because this was always an "uncaught exception", even if used within try/catch
},
200: function (xhr) {
// Do nothing here - put result into cache regardless of status code
}
}
});
requestCache[apiUrl] = result; // save the JSON data into cache
}
return requestCache[apiUrl];
}
// Called by page on load
function LoadJsonData() {
LoadDataFromApi('/api/GetFoo?Row=10')
.then(function (data) {
RenderChart(data, 'Removed for legibility');
})
.catch(function (error) {
console.log('Promise catch: ' + error);
});
LoadDataFromApi('/api/GetFoo?Row=10') // this returns cached data because API has already been hit
.then(function (data) {
RenderChart(data, 'Removed for legibility');
})
.catch(function (error) {
console.log('Promise catch: ' + error);
});
LoadDataFromApi('/api/GetBar')
.then(function (data) {
RenderChart(data, 'Removed for legibility');
})
.catch(function (error) {
console.log('Promise catch: ' + error);
});
}
解决方案
按照您在此处.fail()
的第一个链接中的说明使用
取决于你的 jQ 版本
“弃用通知:jqXHR.success()、jqXHR.error() 和 jqXHR.complete() 回调从 jQuery 3.0 开始被删除。您可以使用 jqXHR.done()、jqXHR.fail() 和 jqXHR.always () 反而。”
编辑:你的错误回调应该接受 3 个参数,所以让它这样
function(jqXHR,textStatus,errorThrown ){}
推荐阅读
- r - 如何查看由 for 循环生成的特定训练集和测试集?
- sql - BigQuery:使用 DML 原子地替换日期分区
- git - 如何仅合并来自另一个分支的一些文件
- android - react-native-udp Sochets.createSocket 未定义对象
- excel - 整个工作簿的 SUMIF
- java - Javadoc @link 到 Kotlin 类
- r - R闪亮的checkboxGroup在地图上绘制数据
- laravel - Laravel 5.4 Route [login] 未定义
- scala - 什么可以在尾递归功能中炸毁我的笔记本电脑?
- f# - 是否可以重复一个数组?