Cancel the search request in Angular and Restangular if a newer one is received

Recently, I've encountered a slow server while trying to pull data from a service using a restangular call. In light of this, I'm exploring ways to potentially abort the call (or just the promise) if a newer call is made, allowing my service to use the most up-to-date information available. Here's the snippet of code for the service call:

  MySearchService.prototype.search = function(query) {

           return $q(function(resolve, reject) {
               var url = '/services/search';
               Restangular.oneUrl(url, url)
                    .customPOST(query)
                    .then(resolve)
                    .catch(reject);
           });
  };

I had an idea like this:

.withHttpConfig({hasNewSearch: abort.promise}) <<not sure you can put custom key in here
abort.resolve();

However, I am unsure if that's the correct way to approach it. Is there a way to cancel the call if a newer request is initiated? It might be related more to the promise aspect rather than restangular itself. Any insights or advice on this matter would be greatly appreciated. Thank you!

Answer №1

This problem is actually quite interesting and is commonly referred to as last or flatMapLatest.

// Here we need a solution that focuses on the last result of a function
function lastResult(fn){ // fn returns a promise
  var lastResultValue = null; // the last promise to compare with
  return function(){ 
    // execute the function and update it as the latest call
    lastResultValue = fn.apply(this, arguments); 
    var p = lastResultValue;
    return p.then(function verifyLast(v){ // execute the function upon resolution
        if(p === lastResultValue){ // check if we are still the "last call" when resolved
            return v; // successful execution
        } else {
            // a newer call took place, resolve with its result and ensure no other calls occurred
            return lastResultValue.then(verifyLast);
        }
    });
}

With this implementation, you can use it in scenarios like

MyDataService.prototype.getData = lastResult(function(query) {
           // updated the approach
           return Restangular.oneUrl('/services/data', '/services/data')
                             .customPOST(query);
});

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

Angular - Implement $sanitize for all user inputs

When it comes to my server side, I make sure to sanitize everything that comes in. For my Angular app client side, I've taken the same approach in certain cases, such as with contact forms. However, I'm starting to think maybe I should just appl ...

When a StaticFiles instance is mounted, FastAPI will issue a 405 Method Not Allowed response

Running a FastAPI application has been smooth sailing until I encountered an issue. In my current setup, the application script is as follows: import uvicorn from fastapi import FastAPI from starlette.responses import FileResponse app = FastAPI() @app.ge ...

Using MUI and React, receive multiple files and track their status changes in a form

Hello there, I am currently working on creating an input file form in React with MUI. My goal is to increase the "state" variable by 100/10 every time a file is uploaded, for example, if I upload 10 files. Below is my current code snippet: import { Button ...

ReserveYourSpot: Effortless Seat Reservation with AngularJS at the Click of a Button [GIF]

ReserveYourSpot: An innovative AngularJS application designed to streamline the process of reserving seats for a movie show, similar to popular platforms like BookMyShow. https://i.stack.imgur.com/PZk1I.gif Interactive User Functions (Use Cases): A ...

Getting the true height without needing jQuery

let element = document.getElementById('test'); console.log(element.scrollHeight); <div style="height: 30px;" id="test"> <p>ffffffffff</p> <p>gggggggggg</p> ...

Eliminate any repeated elements within the nested arrays found within an array of objects

Looking for a way to eliminate duplicates in this array structure. While mapping over arr, the values from each nested array within the objects are retrieved. However, I want to address and filter out any duplicate values. Current Result: bye hello hello ...

Refreshing Slickgrid: Updating grid data with data fetched from an AJAX source

Within the app I am developing, there exists a data grid alongside select boxes that allow users to set filters. Upon selection of these filters, an AJAX call is made to retrieve a new array of data from the server. The challenge I currently face is wipin ...

Is there a way to send a variable to PHP and execute it on the current page?

I need to integrate an inventory search feature on a local clothing store's website. The challenge lies in setting up the PHP script that pulls and organizes the data to run on the same page as the search form itself. Given my limited experience with ...

What is the process for capturing input values when the enter key is pressed?

Is there a way to submit a form on Enter key press without refreshing the page? Below is my code snippet: PHP code: <form action="profile/update_profile" method="post" id="business_name_data"> <input type="hidden" name="business_name" id="busi ...

Choose an option to modify the URL

I am trying to implement a select form element with values ranging from 1 to 7+. When the user selects "7+", I want the URL to redirect to emailForm.php. How can I achieve this functionality? The other options selected should be captured when the user clic ...

"Applying CSS styles to highlighted text using jQuery - how can I do it

Struggling to style selected text with CSS? Here's what I've tried so far without success in Firefox. $(document).keyup(function(){ savedRange = selection.getRangeAt(0); $(savedRange).wrap('<span style="color:red"></span>' ...

Filtering in AngularJS using the ng-repeat directive allows you to iterate over an object

I am trying to figure out a way to determine if each movie in the array belongs to the selected category. The movies array contains objects with various properties, including a 'categories' property which is an array of categories that the movie ...

Is there a way to quickly convert a deconstructed object into a specific type with just one

const { myFunc } = param[0].execute; Is there a way to convert myFunc to a string? This approach is ineffective const { myFunc } = param[0].execute as string; ...

Obtaining information from a local JSON file in AngularJS

I'm facing some issues with retrieving data from a JSON file using the structure below. In my controller.js file, I've written: var controllers = angular.module('hotels.controllers', []); controllers.controller('AppCtrl', f ...

What is the best way to dynamically assign classes to a single <li> element in Meteor when an event occurs?

I'm a newcomer to the meteor framework and I'm attempting to create a project where clicking on the name within a <li> element changes the background color to yellow. When another <li> element is clicked, the previous one should rever ...

Is there a way to transform a dynamically created JavaScript table into JSON or XML format and then store it as a file?

A dynamic table of properties is created in JavaScript using a function: // update table PropertyWindow.prototype._update = function (text) { if (text === void 0) { text = "&lt;no properties to display&gt;"; } this._propertyWindow.html(text); ...

Using an array that is returned from a function in Node.js: a beginner's guide

One of my challenges in Nodejs is dealing with a function that returns a list of recipients: var recipientList = []; userService.listUser().then( result => { var listPSID = result.filter(result => !'279'.includes(result)); recipien ...

In React/JavaScript, the array variable defined outside the component is having props added to it multiple times

After entering new data, I want to add it to an array called DUMMY_MEALS outside the component and display it as a list. The issue I am facing is that the 'data' object is being added multiple times to DUMMY_MEALS and rendering duplicates on the ...

Tips for customizing the cursor to avoid it reverting to the conventional scroll cursor when using the middle click

When you wish to navigate by scrolling with the middle mouse button instead of using the scroll wheel, simply middle-click and your cursor will change allowing for easy scrolling on web pages. Even though I am utilizing style="cursor: pointer" and @click. ...

Yeoman - A guide for integrating an express server task into Gruntfile.js from the generator-angular template

Currently, I am diving into the world of Grunt and attempting to integrate an Express server into my AngularJS application that was initially created with Yoeman. I've made adjustments to the following task as shown below: grunt.registerTask('s ...