最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot .catch() an error when using Jquery.ajax().then() - Stack Overflow

programmeradmin6浏览0评论

I am hitting a number of API's from JQuery, and caching the result of each so that the data can be re-used multiple times in the page to render some dashboard widgets in different formats.

The problem is that if an API returns a 500 status code with error, I don't want to try and draw the widget, but capture the error in a friendly way.

However, I cannot figure out how .catch works with the JQuery.ajax() function. After reading here, here, here, here and a dozen others, I've got so far but always get the same console error:

TypeError: LoadDataFromApi(...).then(...).catch is not a function

I've tried to ment the code to explain what I'm trying to do at each stage. Please somebody explain why the whole .catch thing isn't working for me.

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

I am hitting a number of API's from JQuery, and caching the result of each so that the data can be re-used multiple times in the page to render some dashboard widgets in different formats.

The problem is that if an API returns a 500 status code with error, I don't want to try and draw the widget, but capture the error in a friendly way.

However, I cannot figure out how .catch works with the JQuery.ajax() function. After reading here, here, here, here and a dozen others, I've got so far but always get the same console error:

TypeError: LoadDataFromApi(...).then(...).catch is not a function

I've tried to ment the code to explain what I'm trying to do at each stage. Please somebody explain why the whole .catch thing isn't working for me.

// 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);
        });
}
Share Improve this question asked Oct 12, 2018 at 10:26 EvilDrEvilDr 9,59020 gold badges80 silver badges145 bronze badges 5
  • 1 Also jquery has it's own implementation of promises (basically because they were doing this before promises became a thing). It requires a fail not catch call. – Liam Commented Oct 12, 2018 at 10:34
  • I know this is a big ask, but my head is spinning from a day on this. Could you please help apply that re-structure so I can see this in action? It's really important that the cache is respected, so API's aren't called twice unnecessarily, and it's this plexity that's making this so much more difficult to grasp. – EvilDr Commented Oct 12, 2018 at 10:36
  • 1 @Liam I think you're wrong - look at the implementation of LoadDataFromApi - it evidently returns jQuery.ajax() result, not the cache object itself :) – SzybkiSasza Commented Oct 12, 2018 at 10:38
  • Yes, I've just seen that @SzybkiSasza , sorry – Liam Commented Oct 12, 2018 at 10:38
  • Obviously not enough coffee this am. – Liam Commented Oct 12, 2018 at 10:40
Add a ment  | 

2 Answers 2

Reset to default 11

Use .fail() as described in your first link here

Depending on your jQ version

"Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.plete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead."

EDIT: You error callback should accept 3 arguments, so make it so

function(jqXHR,textStatus,errorThrown ){}

JQuery does not return typical promise, it's$.Deferred in that case:

  • http://api.jquery./jquery.ajax/
  • http://api.jquery./category/deferred-object/

More on that here, with answers: Deferred versus promise

发布评论

评论列表(0)

  1. 暂无评论