Terminate the XHR request in Cujojs Rest.js

Seeking a solution to cancel requests using cujojs/rest when a new one comes in. Trying to ensure only the latest request is processed, while aborting all other unfinished ones.

Previously used beforeSend method with another tool for this task. Now struggling to implement the cancel method in cujojs/rest to achieve the same result.

Need to manage multiple page requests effectively to avoid unnecessary data loading. Looking for guidance on how to utilize the cancel method appropriately.

/users?page=1 -> should be canceled
/users?page=2 -> should be canceled
/preferences  -> should NOT be canceled
/users?page=3 -> should be canceled
/users?page=4 -> should go through as its the last one

Appreciate any assistance provided.

Answer №1

Unfortunately, there is a lack of proper documentation on this topic as far as my research shows. However, based on the source code provided, it seems that you should be able to implement something like the following:

// Assuming you have defined **this.request** somewhere in the constructor to store the request value, which initially defaults to an empty object {};

fetchCollection: function(id) {

var that = this;
var url = 'collections/' + id;

if( Object.keys( that.request ).length !== 0 ) {

    if( 'function' === typeof that.request.cancel )
         that.request.cancel();
    else
         that.request.canceled = true;

  // Resetting the value back to default {} here
  that.request = {};


}
that.request.path = url;

return client( that.request ).then(
        function(response){
            that.collection = response.entity.data;
        },
        function(response){
            console.error(response.status.code, response.status);
        }
    );
},

If this solution works for you, I can provide an explanation of why it works.

Once confirmed that the solution works, I will explain the process using pseudo-code:

Within the client( request ) function from cujojs, the following steps are taken before any action is performed:

  1. It checks if request.canceled exists and is set to true

  2. If the condition is met, the request is aborted

If request.canceled does not exist, the process continues to the next step

  1. cujojs defines a request.cancel function that can abort the request before it is sent (we do not need to focus on subsequent steps as our intention is cancellation)

We are leveraging JavaScript's ability to pass variables by reference. Passing variables by reference means that when we give the create() function a variable like request, the function uses the same variable within itself rather than creating a new copy of the variable. This manipulation allows us to directly influence the request variable used by cujojs during the execution of the create() function.

Knowing that cujojs has two ways to cancel a request, and that we can manipulate the request variable after it has been received by the create() function, we perform a simple check on our end:

  1. We verify whether this.request is empty (indicating no previous requests have been sent yet)

  2. If it is not empty, we check if cujojs has already defined the .cancel function on our request variable by checking 'function' === typeof request.cancel

  3. If the function is defined, we use it to cancel the previous request. If not, we know that cujojs is moving forward to check the .canceled variable on our request, so we set it to true with this.request.canceled = true

  4. After cancelling the request, we assign a fresh value of {} to the request variable, thereby losing reference to our previous manipulated request variable

I may not excel at explaining concepts, but I hope this breakdown clarifies the process for you. Understanding these nuances can greatly benefit your development endeavors.

Happy coding!

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

Load the div first before delaying the load of the next element using jQuery

Hey there! I'm currently working on a gallery with left-floated divs, where each picture serves as the background for the div. What I'd like to achieve is having each picture load with a slight delay; meaning the first picture loads, then waits f ...

The text in the AJAX file is visible in the network tab, but it is not appearing on the screen

//server.js Here is my node.js server code. I am currently focusing on understanding the basics of Node before diving into Express. Backend development in general can be a bit confusing for me. var http = require('http'); var fs = require(&apos ...

Information is not readily available through API utilization

For my project, I am implementing a search filter feature. While I can successfully retrieve data by querying the API, no data is displayed when consuming the API on the MVC side. API Controller, [HttpGet("ListExpenseByAccountingSearch/{search}" ...

What is hindering me from fetching the information stored in my json file?

Currently, I am delving into learning AngularJS by working on a simple webpage for a company. This page will showcase products that are fetched from a json file. Following a tutorial from the AngularJS website, which covers the exact task I aim to achieve, ...

Selecting the optimal data structure: weighing the benefits of using boolean check versus array .include (balancing performance and redundancy

My objects can have one or more properties assigned, with a total of 5 different properties in my case. To illustrate this, let's use a simple movie example where each movie can be assigned from 5 different genres. I have come up with two methods to ...

Transform HTML invoices into emails

I am currently working on developing an ERP system. I have an HTML invoice that needs to be converted into a PDF and sent via email. My question is regarding how to construct the invoice using jQuery & AJAX, convert it into a PDF format, and then send it ...

Review the Drawer Item's Render Method

I have been using react-native with expo and following a specific guide closely: Is there an alternative way to implement this without the use of icons at the moment? Upon compiling, I encountered an error regarding the Render Method of DrawerItem. I&apo ...

I'm having trouble grasping the concept of this asynchronous behavior

After reviewing the output provided, my initial expectation was for working to be displayed between the lines of begin and end. Here is the rule: Is there a possible solution to achieve this outcome without modifying the app.js file? app.js const se ...

Steps to conceal a div when a particular property is detected in one of its child elements (img)

On my website, I have a label and a checkbox. The checkbox in question is created by Salesforce (thus the dynamic appearance of the span id). This excerpt shows the code from my webpage: <div class="fds" id="checkinput"> <label>Additional Rev ...

Steps to insert additional characters surrounding the innerhtml of an h2 element

After extensive searching, I still can't seem to figure this out. It's possible I'm overlooking something very obvious, and for that, I apologize. My current challenge involves adding two specific characters to multiple h2 elements. While I ...

Three.js - Controlling Visibility of Text in troika-three-text with Clipping Planes

Has anyone successfully clipped troika-three-text for threejs using clipping planes? I'm having trouble getting it to work. import { Text } from 'troika-three-text' const minClippingPlane = new THREE.Plane(new THREE.Vector3(0, -1, 0), 1) c ...

Error encountered in SelectInput.js file of React MUI 4: line 340 - TypeError: Unable to access properties of undefined (specifically 'value')

An issue arises when an empty array is provided as the options. The error message: SelectInput.js:340 Uncaught TypeError: Cannot read properties of undefined (reading 'value') at SelectInput.js:340:1 at Array.map (<anonymous>) ...

Using JQuery's $.ajax() method to send a post request and pass data to invoke a specific method in

I'm currently in the process of learning JQuery and encountering some challenges with utilizing the $.ajax() function. My goal is to send data to a controller for processing. During my debugging of the JQuery, it seems that the ajax call isn't b ...

Is there a way to retrieve the final word following a unique character?

Currently, I have this: \- (.*) When analyzing the text below: September 2014 - Media I am trying to extract "Media", but instead I am retrieving "- Media" ...

Adjusting the value of a user form with multidata in PHP and Javascript

I am looking for guidance on how to modify the value of an input in a form that contains multiple data entries. Here is my form: <form method="post" action="pax-flight.php#pax-flight" class="paxform"> <input type="hidden" value="{"data":{"us ...

Ways to avoid form submission using jQuery

A unique shortcode has been developed to create a custom input: function generateCustomInput() { $output = " <div data-role='controlgroup' data-type='horizontal' data-mini='true'> <button ...

PHP can be executed and accessed directly from JavaScript without the need for any form submission

While I have come across a lot of information on PHP post/get methods for transmitting data, I find myself stuck with an interesting issue that requires some assistance. My HTML page contains data in different inputs, and I run algorithms on the JavaScrip ...

Artboard: Easily navigate through pictures

As part of a school assignment, I wanted to create an interactive story where users can click through images using the UP and DOWN buttons. However, I am facing an issue with my If function overriding the previous function. I envision this project to be a ...

jQuery image resizing for elements

I have successfully adjusted the images in the gallery to display one per row for horizontal orientation and two per row for vertical orientation. Now, I am facing a challenge in making the images scalable so they can resize dynamically with the window. A ...

Prevent the beforeunload dialog box from appearing

Looking for a solution that is compatible with all browsers and operating systems. Referring to this resource https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload This is what I have so far: window.addEventListener("beforeunload", function ( ...