我从 JQuery 访问了许多 API,并缓存了每个 API 的结果,以便可以在页面中多次重复使用数据,以不同的格式呈现一些仪表板小部件。
问题是,如果 API 返回带有错误的 500 状态代码,我不想尝试绘制小部件,而是以友好的方式捕获错误。
但是,我无法弄清楚 .catch
如何与 JQuery.ajax()
函数一起使用。看完here , here , here , here和其他十几个,到目前为止我已经得到了,但总是得到相同的控制台错误:
TypeError: LoadDataFromApi(...).then(...).catch is not a function
我尝试对代码进行注释以解释我在每个阶段想要做什么。请有人解释一下为什么整个 .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()
here
取决于您的 jQ 版本
"Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead."
编辑: 你的错误回调应该接受 3 个参数,所以就这样吧
function(jqXHR,textStatus,errorThrown ){}
关于javascript - 使用 Jquery.ajax().then() 时无法 .catch() 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52777536/