AngularJS and synchronized queueing of API requests

I am attempting to develop a synchronized queue for API requests using AngularJS.

class x {
    public y() {
        ...
        restRequest();
    }
}

I have this class, along with a whiteboard canvas. When I drop an entity onto the canvas, the method 'y' is called.

For example, if I quickly drag and drop 5 entities, it generates 5 API requests for me.

I wish to implement the 'restRequest' in a synchronous queue so that when I drop 5 entities, it will form a queue of 5 requests where request 1 will start first, followed by the next request upon completion, and so on (synchronized queue).

I attempted to achieve this with the following code:

class x {
    private queue: object = {};
    
    public y() {
        const uniqueId: number = Date.now();
        
        let queueIsEmpty = _.isEmpty(this.queue);
        
        const func = setInterval(() => {
            if(queueIsEmpty) {
                this.queue[uniqueId] = true;
                clearInterval(func);
                restRequest();
            }
            queueIsEmpty = _.isEmpty(this.queue);
        }, 1000);
    }
    
    private restRequest() {
        
    }
}

However, this approach is incorrect as there is a race condition – after the first request finishes, it can enter the block four times altogether for the remaining queued requests.

So, how can I create a synchronized queue of API requests? Thank you.

Answer №1

This code snippet provides a simple solution:

dataQueue = [];
active = false;

addData(data) {
  if (this.active) {
    this.dataQueue.push(data); // enqueue data for later processing
  } else {
    this.processData(data); // process data immediately
  }
}

processData(data) {
  this.active = true;
  return this.$http.post(...).then(() => {
    this.active = false;
    this.onProcessingComplete()
  }); // how to handle errors is your call
}

onProcessingComplete() {
  // if there are more items in the queue, process next one
  if (dataQueue.length) {
      this.processData(dataQueue.shift());
  }
}

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

Sending an array of properties to a child component

I am attempting to pass an array of objects from a parent component to a child component as a prop, then iterate over it using map and display the items in the child component. However, when I try to use map on the array nothing is happening, even though ...

What is the best way to manage multiple arrays?

There is an array containing multiple arrays within it. I am trying to locate the specific sub-array that contains an object with name: "tax-payer-identification". Once found, I need to set the variable's value from required: true to false. ...

Navigating forwards in Angular 7 causes loss of state

I have a situation with my angular 7 Ionic application. When I navigate to a page, I use the following code snippet: navigateToDetail(entity: User) { const navigationExtras: NavigationExtras = { state: { entity, entityId: entity.id ...

Use an array to store nested JSON fields

I'm currently seeking to enhance my proficiency in utilizing JavasScript, React, and Material-UI. I am faced with the challenge of sorting my table using a nested JSON structure and I am encountering difficulties with assigning the JSON fields to my a ...

Experiencing issues with Panolens.js failing to load images

Currently, I am in the process of setting up a basic 3D image viewer using Panolens.js. Despite following the example provided in the documentation, I am encountering console errors during the loading process. This is my initial attempt at working with equ ...

Trying to use 'cpa' before it is initialized will result in an error

I encountered the error stated above while using this particular route: router.put('/edit/:id', async (req, res) => { const cpa = await CPASchema.findById(req.params.id).then(() => { res.render('edit', { cpa:cpa }); cons ...

Express Node fails to launch

I recently decided to try my hand at Express and learn more about it. However, I encountered an issue while trying to start a server. Initially, I attempted to access 127.0.0.1:8080 through Express but nothing seemed to be happening. Although I copied most ...

combine blank cells in table generated with vuejs

I am attempting to display a table of students where each column represents a subject, and underneath each column are the names of the students who failed in that particular subject. The challenge I am facing is that my data is structured in rows instead o ...

Determine if the object's value is present

My current JavaScript setup looks like this: var NAMES = []; function INFO(id,first,middle,last){ var newMap = {}; newMap[id] = [first, middle, last]; return newMap ; } Next, I have the following code block: for (var j = 0; j < NUMBER.leng ...

"Using AngularJS to display a blank option as preselected in an ng-option

Having an issue with displaying a preselected value as the selected option in my select element. Check out the code below: <select ng-model="data.company" ng-options="company as company.name for company in companies"></select> $scope.compani ...

Adjusting Picture Sizes to Fit the Dimensions of a Photo Frame

Currently, I am in the process of developing a website that incorporates two distinct image types: Portrait photos Landscape photos As you can see, there are two different categories of images: Square Rectangular I need to resize all the phot ...

What is the significance of employing the `var` keyword in Vue.js?

As I dive into tutorials and browse through code snippets while immersing myself in learning this framework, I've noticed a common trend - the use of var for declarations. This practice seems prevalent across resources, including the official Vue docu ...

Utilizing Node.js for autonomous socket connections

Exploring the world of Node.js is a new adventure for me, so please bear with my beginner's mindset :) Currently, I have a web application that uses a combination of Node/Angular/Express to invoke C++ functions from a DLL on the server and deliver th ...

Tips for stopping ajax requests from automatically following redirects in jQuery

When utilizing the jQuery ajax functions to connect with a web service, I encounter an issue where the server redirects the response to a page with a 200 status code instead of providing a proper status code indicating an error. Unfortunately, I am unable ...

You need to pass a function as the first parameter when using passport-local-mongoose as a schema plugin

I've been struggling with implementing passport-local-mongoose in my server. I followed a tutorial video but encountered an issue that wasn't addressed in the video - even though my database is connected to mongodbatlas. The error message "First ...

JQuery is unable to validate a form that is being loaded from an external HTML file

I'm encountering an issue where my form imported into a separate HTML file is not validating using JQuery's $(form).validate() plugin. After following the guidance provided in this question, I successfully managed to get the form working. Howeve ...

Using PHP to reset variables for dynamic display in JavaScript

I've been working on retrieving values from a database and storing them in JavaScript variables. While I was successful in accomplishing this task, I encountered an issue when the values in the database are updated - the values of the variables remain ...

Ensure that the view is only updated once the JSON has been completely received from the AJAX call in AngularJS

Just starting out with angularJS and still in the learning phase. I'm currently working on creating a navbar for the header that will fetch data from an ajax call. The issue I'm facing is that it displays {{obj.pageData}} until the data is fully ...

a function that repeats every single second

A challenge I am facing is creating a countdown timer with a time that refreshes every second. My current implementation uses setInterval, but it only seems to run once instead of every second. Can anyone help me identify the issue in my code? var countDo ...

Differences in how line breaks are handled in script output have been observed when comparing Atom and Notepad

Currently, I am utilizing a small script that generates a .txt file and inputs some data into it. Strangely, when I open the .txt file in Atom, the content appears on separate lines as I intended. However, when I access the same file in notepad, all the co ...