Keep sending HTTP requests until a 404 error is received

I need to keep sending http requests until I receive an error 404 response from one of them.

There are a total of 21 pages and my current setup looks like this:

_getAll = function () {

var promises = [];
var pages = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21];
angular.forEach(pages, function (page) {
    var deffered = $q.defer();
        $http({
            url: 'http://api.tvmaze.com/shows?page=' + page,
            method: 'GET'
        }).
            success(function (data) {
                console.log("OK")
                deffered.resolve(data);
            }).
            error(function (error) {
                deffered.reject(error);
                console.log(error.status);
            });
        promises.push(deffered.promise)
    })
    return $q.all(promises);
},

However, when trying to access , it returns a 404 error.

Is there a way to continue making http requests until a 404 response is received? Whether through looping or another method?

Answer №1

To handle asynchronous calls efficiently, implementing a while loop wouldn't be suitable as it would attempt to make calls to numerous pages in milliseconds without even loading the initial page. It is essential to wait for each page request to finish before proceeding to load the next one.

An alternative approach is to create a function responsible for fetching a single page and then triggering it with the subsequent page number upon successful loading. When an error occurs, execute a final success callback function and return the collected data.

_getAll = function(callback) {

    var pageData=[];

    function getPage(page) {
        $http({
            url: 'http://api.tvmaze.com/shows?page=' + page,
            method: 'GET'
        }).
        success(function (data) {
            pageData.push(data);
            //get next page
            getPage(page + 1);
            console.log("OK")
        }).
        error(function (error) {
            //Hit an error. All done. Trigger callback.
            callback(pageData);
            console.log(error.status);
        });
    }

    //get first page
    getPage(0);
}

//usage:

_getAll(function(data){
    //this function will trigger once we get an error
    //data will be an array of all of the pages data
   console.log(data); 
});

Answer №2

Implementing proper error handling with $q.all will allow you to achieve this task efficiently. Below is the code along with an explanation:</p>

<pre><code>_getAll = function() {

    var pages = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21];
    return $q.all(pages.map(function(page) {
        return $http({
            url: 'http://api.tvmaze.com/shows?page=' + page,
            method: 'GET'
        })
        .then(function(response) {
            return response.data;
        }, angular.noop);
    }))
    .then(function(data) {
        data.pop();
        return data;
    });
};

Note that using angular.noop in the then callback of individual requests helps in handling failed requests (such as status 404) effectively. This allows for a smooth recovery from error situations where there are no more pages available. The resulting array of data does not contain any undefined values as the last element by removing the unnecessary undefined element returned by angular.noop for 404 pages.

Check out the Demo: http://plnkr.co/edit/CR711Js1KvrvnvKDonXK?p=preview

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

utilize jquery ajax to input various data

I am attempting to include multiple data in a jQuery ajax call. However, my current implementation is not working as expected. The data fetched is taken from the following span: <span id="<?php echo $tutorial_id; ?>" modes="<?php echo $modese ...

An error occurred when attempting to access data within a variable that is undefined, resulting in a TypeError at the errorHandler function

Every time I attempt to send a post, patch, or put request, I keep getting this error. However, there are no issues with get requests. TypeError: Cannot read properties of undefined (reading 'data') at errorHandler (/home/joe/Documents/mypro ...

Detecting mistakes using ES6 assurances and BookshelfJS

I'm working on implementing a simple login method for a Bookshelf User model in an ExpressJS application. However, I am facing issues with handling errors from the rejected promises returned by the login function in the User model. While referring to ...

Display PHP output for a brief moment

Here is the URL: http://www.example.com/?req=welcome. In PHP, to retrieve the parameter req, you can use the following code: echo $_GET['req']; The message will be displayed in the body but it should disappear after one second. What is the be ...

The pagination feature of the material-ui data grid is experiencing issues with double clicks because of its compatibility with the react-grid-layout library for

I am currently using the react-grid-layout library to manage the resizing of both charts and a material-ui data grid table. However, I am encountering an issue where when clicking on the table pagination arrow, it does not work properly. I have to click tw ...

Transform HTML components into visual representations (on the server)

I am looking for a way to convert dynamic HTML elements into image files such as jpg or png. I do not want to capture a screenshot of a webpage or a static HTML file. My goal is to achieve something similar to the following, but executed on the server-sid ...

Display a modal upon successful validation of a form

As a newcomer to JavaScript and Bootstrap, I have a specific requirement: 1. When a user clicks the submit button, 2. The form needs to be validated using the entry_check() function. 3. Upon successful validation of the form, a Bootstrap modal should be op ...

Discovering the present width of an Angular element after it has been eliminated

Imagine you have a horizontal navigation bar coded as follows: HTML: <ul> <li ng-repeat="navItem in totalNavItems">{{name}}</li> </ul> CSS: ul, li { display: inline-block; } The data for the navigation items is fetched from thi ...

Error 414: The URL exceeds the maximum length and cannot be processed

I am currently utilizing vuejs and sending an axios request to the server in order to download a csv file. download() { var that = this //this.records = [{id: 1, name: 'Jack'}, {id: 2, name: 'Jacky'}, {id: 3, name: &apos ...

Replace a string in an array using JavaScript

I may be overlooking something very obvious, but here is my dilemma. I am trying to convert [ 'hr' ] into [ '* * *' ]. This is what I tried: var hr = jsonml[i] console.log(hr) // outputs: [ 'hr' ] hr.replace(/hr/g, '* * ...

Inspecting the final element of my jQuery slider

I've been working on a jQuery slider where I add the class "currentmemory" to each child of my memory2container to show which slider is displayed. The issue arises when I reach the last slider; instead of looping back to the first one and starting ov ...

Error: The promise was not caught due to a network issue, resulting in a creation error

I'm trying to use Axios for API communication and I keep encountering this error. Despite researching online and attempting various solutions, I am still unable to resolve the problem. Can someone please assist me? All I want is to be able to click on ...

Create HTML elements based on the information in a JSON object

My goal is to create span elements for each word in my subtitle text, which is stored in a JSON object. Here is the JSON data I am working with: var sub_info = [ {'start': 3.92, 'end': 6.84, 'words ...

I am experiencing issues with local storage getItem() function not functioning properly within NUXT JS

Currently working on creating a shopping cart using nuxt js. Successfully able to store the cart data in local storage, but facing difficulty in retrieving the data. Refer to the screenshots for more details: https://i.sstatic.net/X7dL9.png https://i.sstat ...

Method for transmitting JSON array from Controller to View using CodeIgniter

I have a function in my controller: function retrieveAllExpenses() { $date=$this->frenchToEnglish_date($this->input->post('date')); $id_user=$this->session->userdata('id_user'); $where=array('date&ap ...

Tips for exiting a function at a particular point

How can I ensure that my async function only returns at a specific point and not void at the end? const fun = () => { const list = []; let streamFinished = 0; let streamCount = files.length; await fs.readdir(JSON_DIR, async(err, files) => ...

Error encountered during Angular unit testing: Unable to read the 'id' property of a null value. (Jasmine, Karma)

I am currently working on writing unit tests for a specific component in my Angular application. The component uses a currentUser variable both in the component logic and the HTML template. I have hardcoded this variable by mocking it in every test using c ...

"Error occurs when passing data back to main thread from a web worker: undefined data received

Hello, I’ve been experimenting with using a web worker to retrieve data and send it back to the main thread. However, I've encountered an issue with my code not working as expected. onmessage = (e) => { console.log(e); if( e.data[0] === &apos ...

Trouble updating document with MongoDB updateOne when using ID as filter

I need to update a property value of a specific document by sending a request to my NextJs API using fetch. // Update items in state when the pending time in queue has passed, set allowed: true items.map((item) => { const itemDate = new Date(item.adde ...

Utilizing hooks in node.js functions

Is there a way to apply before and after hooks on a function? I need these hooks to trigger whenever the function is called. While Express.js middleware concept works for routes, I require similar hooks for functions on the server side. function main(){ ...