首页 > 解决方案 > 使用 Jquery.ajax().then() 时无法 .catch() 出错

问题描述

我从 JQuery 中访问了许多 API,并缓存了每个 API 的结果,以便可以在页面中多次重复使用数据,以以不同的格式呈现一些仪表板小部件。

问题是,如果 API 返回 500 错误状态代码,我不想尝试绘制小部件,而是以友好的方式捕获错误。

但是,我无法弄清楚.catch该功能是如何工作的JQuery.ajax()。在阅读了 herehereherehere和其他十几个之后,我到目前为止,但总是得到相同的控制台错误:

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);
        });
}

标签: javascriptjqueryajaxpromise

解决方案


按照您在此处.fail()的第一个链接中的说明使用

取决于你的 jQ 版本

“弃用通知:jqXHR.success()、jqXHR.error() 和 jqXHR.complete() 回调从 jQuery 3.0 开始被删除。您可以使用 jqXHR.done()、jqXHR.fail() 和 jqXHR.always () 反而。”

编辑:你的错误回调应该接受 3 个参数,所以让它这样

function(jqXHR,textStatus,errorThrown ){}

推荐阅读