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

Verifying that the data has been successfully saved using JavaScript

When a user submits a small chunk of data via AJAX using a standard update action and a remote form, the information is sent to the action as javascript. The response is then rendered in javascript utilizing format.js. def update @message = Message.wher ...

Guide on utilizing $q for retrieving a promise from a $broadcast within angularJS

Currently, the controller code I've written is structured like so: $scope.spAPI.load(id).then(function(result){ var deferred = $q.defer(); if(result !== undefined){ deferred.resolve($rootScope.$broadcast("onSpLoaded", result)); } return de ...

Transferring an array from JavaScript to PHP, encountering an issue with determining the length

I'm having an issue passing an array from my .js file to a PHP file. In JavaScript, the array is structured as follows: theBlock[0 - 79] with color, x, and y values. For example, theBlock[10].color or theBlock[79].x The data is sent using the follow ...

Windowing box inside a container box

I am looking to implement scrolling for just the "chat-messages" div within the "chat-bar" div on my site. I want only this specific section to be scrollable, while the rest of the site remains stationary. Currently, I have to scroll through the entire pag ...

Ensuring the integrity of ASP.NET Webforms using AngularJS

When using AngularJS validation status, I am faced with the issue of needing to reference the form by its name. However, the current form does not have a name, and I am unsure of how to set one without resorting to using JavaScript, which is not my preferr ...

How can you establish a default value on a paper select in Polymer?

I have a paper-select element that I want to customize with a default value when the page loads or after a specific event occurs. <dom-module id="custom-paper-select"> <template> <paper-select id="select-input-1" multiple ...

How to Upload Your Avatar Image with the Stream-Chat API from GetStream.io

I am currently in the process of developing a Stream-Chat API project and I want to allow users to upload images directly from their devices. Upon testing, everything seems to be working fine, but the uploaded image is not displayed - only the default avat ...

What method does the framework use to determine the specific API being accessed?

How can the framework determine which API is being accessed? app.get('/user/:userId/name/export', function (req, res) { var userId = req.params.userId; } app.get('/user/:userId/name/:name', function (req, res) { var userId = req ...

Error! D3.js is throwing an Uncaught TypeError because it cannot find the function .enter(...).append(...).merge

Currently, I am facing an issue while attempting to construct a table with multiple nested dropdowns using d3.js. The problem arises when switching from a newer version of d3 where my code functions flawlessly to d3.js v3. Upon replacing the newer version ...

The connection between AngularJS and the Node.js server is struggling with sending input data, resulting in a 404 error message

Why is the HTTP address not found? I am seeing these mistakes in the console: POST http://localhost:3000/api/message 404 (Not Found) angular.min.js XHR finished loading: POST "http://localhost:3000/api/message". angular.min.js Error " ...

Exploring the architecture of Redux-thunk and validating the impact of side effects

I've been using redux-thunk and I'm not entirely sure if my side effects (specifically the showAlertError function) are structured properly. While my jest test setup seems to be fine at first glance, I encountered an error: jest.fn() value mus ...

Dynamic class name changes in Angular.js based on JSON object

I am trying to dynamically change the class of an <li> element based on the category value I am getting, but for some reason the class name won't update. Here is the code snippet: <div id="content"> <ul id="container" ng-controller ...

Challenge with JavaScript personalized library

No matter how many times I review my code, I find myself perplexed. Despite my efforts to create a custom library of functions from scratch (shoutout to stackoverflow for guiding me on that), the results are leaving me puzzled. A javascript file is suppose ...

I am able to successfully receive accurate data in JSON format, however I am facing difficulties binding it to a jquery

I am struggling with integrating data fetched in JSON format using $.ajax into a table using jquery's datatable. Below is the JavaScript code I have been trying: $(document).ready(function () { $.ajax({ type: "POST", url: "Result.aspx/getUser ...

Removing the Login button from the layout page after the user has logged in can be achieved by

I am currently developing an MVC application in Visual Studio 2012. Within my layout page, there is a login button that I would like to hide after the user successfully logs in. Despite my attempts, the method I am using doesn't seem to be working. Ca ...

Enhance your WordPress menu with additional attributes

Currently, I am implementing a lightweight lightbox script on my WordPress website. My goal is to have one of the main navigation buttons open a Vimeo link in the lightbox. According to the lightbox documentation, I need to "Add the 'data-lity' a ...

Looking to bring in a non-ES6 library into VueJS without using export statements

Currently, I am faced with an interesting challenge. For a forthcoming VueJS project, we must utilize a library that is quite outdated but there is simply not enough time to redevelop it. The library is essentially a JavaScript file which consists of num ...

Origin Access-Control-Allow Not Recognized

Currently, I am developing a node.js app and have encountered a strange issue: This particular Angularjs snippet... // delete hosts $scope.delete = function(row) { var rowData = { hostname: row.hostname, ipaddr: row.ipAddress, ...

The compatibility between cross-fetch and React Native is currently not supported

I have developed an API wrapper that utilizes fetch to carry out the API requests. To ensure compatibility with Browsers, Node, and React Native, I incorporate cross-fetch. When testing the wrapper in Node, everything works fine. However, when using it in ...

Executing Firebase Cloud Functions to perform write operations within a database event function

Exploring the world of Firebase functions has been an exciting learning journey for me. This innovative feature is proving to be incredibly powerful and beneficial. I'm eager to utilize a function that can capture a database writing event, perform a ...