Davy Jans
Davy Jans

Reputation: 1

jQuery ajax call with 422 state results in chrome / edge console error even though fail function is used

Context

Calling an API from a planner tool to return events for an employer. The API returns a 422 if a certain employer does not have any events (rather strange behaviour, I would just expect an empty array - but I do not have control over that API).

I'm using javascript/jquery (in a cordova app but that should not matter?) and running in browser. All works great if the API returns 1 or more events..

Code snippet

let eventPromises = [];
let projectPromises = [];

let completeEvents = [];

 $.ajax({
        url: baseUrl + `resources/${ID}/events`,
        type: "GET",
        headers: {
            "apikey": apikey
        }
    }).then(function(events) {

        events.entities.forEach(event => {
            eventPromises.push(

                //get Event data
                $.ajax({
                    url: baseUrl + `events/${event[0].entityValue}`,
                    type: "GET",
                    headers: {
                        "apikey": apikey
                    }

                }).then(function(detailedEvent) {

                    projectPromises.push(

                        //Get project data
                        $.ajax({
                            url: baseUrl + `resources/${detailedEvent.entities[0][23].entityValue}`,
                            type: "GET",
                            headers: {
                                "apikey": apikey
                            }
                        }).done(function(project) {

                            let eventObj = new Object();
                            eventObj.eventData = detailedEvent;
                            eventObj.projectData = project;
                            completeEvents.push(eventObj)

                        }));
                }));
        });

    }).then(function() {
        Promise.all(eventPromises)
            .then(() => {

                Promise.all(projectPromises)
                    .then(() => {
                        if (completeEvents != null && completeEvents.length > 0) {

                         //Here everything works and I append some html

               })
            })

    })

Error (in browser console) jquery.min.js:2 GET http://localhost:3000/proxy/https*****events%3FbeginDate%3D01%2F01%2F2021%26endDate%3D16%2F01%2F2021 422 (422)

Question

  1. Does anyone see what I'm doing wrong?

  2. Also feel free to comment on the code. I know it might look strange (the chaining, and could be the reason of the error) but this was the best I could come up with for now. I need to call multiple endpoint to get all data (api does not provide batching or anything).

Thanks for the help.

Upvotes: 0

Views: 80

Answers (0)

Related Questions