Ways to merge various Ajax call data requests from distinct JavaScript files

I have code in a file that is responsible for making Ajax calls. This file is utilized as a function by several other files, each creating a new instance.

Here is the JavaScript code being called:

define(["underscore", "homeop", "domReady!"],
    function (_, homeop, domready) {
         
        var timeout = 500;
        return function (opUrl, opList, onCallback) {

            // IRRELEVANT CODE 
          
          var getFetch = function (optionName) {
                    $.ajax({
                        url: optionsUrl,
                        data: { optionNames: [optionName] }, 
                        type: "POST",
                        dataType: "json",
                        async: false,
                        traditional: true,
                        success: function (data) {
                            _.each(data, function (optionData, optionName) {
                                if (homeop.globalCache[optionName] === null) {
                                    homeop.globalCache[optionName] = optionData;
                                }
                            });
                            
                        },
                        error: function (message) {
                            console.error(message.responseText);
                        }
                    });
                };
          
          self.getInfo = function (optionName) {
            if (homeop.globalCache[optionName] === undefined) {
                    if (!_.contains(homeop.getOption(), optionName)) {
                        getFetch(optionName);
                    }
              
              // MORE IRRELEVANT CODE GOES HERE

          
          

In other JS files, I call the get function; for example

var these = new getOptions(optionsUrl, optionsList, onLoadCallback);
var getOpt = these.get(OptionsUrl);

The issue arises when multiple calls are made to retrieve information from the database, resulting in multiple calls to my JS file. Each new instance of the JS file initiates an ajax call.

Is there a way to consolidate all the calls to 'getOption.js' and wait for them to complete before retrieving data from the database? In essence, how can I synchronize these calls?

Thanks

Answer №1

Here is a helpful suggestion: Consider using a queue instead of a stack in your implementation.

var optionStack = [];
var isAvailable = true;
var getFetch = function (optionName) {
  if(isAvailable){
      isAvilable = false; // function not available now
  }
  else {
    optionStack.push(optionName)
    return;
  }
  $.ajax({
    url: optionsUrl,
    data: { optionNames: [optionName] }, 
    type: "POST",
    dataType: "json",
    async: false,
    traditional: true,
    success: function (data) {
      _.each(data, function (optionData, optionName) {
        if (homeop.globalCache[optionName] === null) {
          homeop.globalCache[optionName] = optionData;
        }
      });

    },
    error: function (message) {
      console.error(message.responseText);
    },
    done: function (){
      isAvailable = true;
      if(optionStack.length > 0){
        getFetch(optionStack.pop());
      }
    }
  });
};

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

The Bootstrap Modal consistently shows the contents of the first record when used within a SQL While Statement

As a newcomer, I am in the process of converting an operational Bootstrap modal that houses a post form. Initially, the modal would open using a button with a specific Id and would always display the FORM contents from the first record found in the SQL w ...

Uncovering the Mystery of Undefined Dom Ref Values in Vue 3 Templaterefs

I am currently experimenting with the beta version of Vue 3 and encountering an issue while trying to access a ref in the setup function. Here is my component: JS(Vue): const Child = createComponent({ setup () { let tabs = ref() console.log(t ...

Unveiling the secret to extracting URL parameters from a POST request using Node.js and Express.js

REQUEST URL http://localhost:9090/rest-api/fetchDetailedProductInfo?prodId=1&tempId=123 fetchDetailedProductInfoEndpoint: function (prodId) { var self = this; var endpointURL = 'http://localhost:9090/ ...

Error: The absence of an element identified by the locator does not cause the protractor spec to fail, but rather it executes successfully

This automation framework follows the page object model and utilizes the async/await approach rather than promises. TypeScript is used, with compilation to JavaScript (protractor) for script execution. Page Object: async addProjectDetails(): Promise< ...

margin-top: automatic adjustment, with a minimum of 50 pixels

I am trying to add a minimum of 50px margin to the top of my footer tag using CSS, but I haven't been successful with the min() function. I'm not sure if I am overlooking something or if there is another correct approach to achieve this. * { ...

Is there a way to utilize Ajax to send an HTTP POST method and fetch the input field values without relying on jQuery or prototype?

I am making progress towards the solution, but I'm struggling with sending an HTTP POST method using Ajax. Understanding this will also be beneficial for my REST project. While there are plenty of online resources available that use Jquery or Prototy ...

Selecting a default option in Angular when the value is present and repeated

My goal is to pass a parameter in the URL to a page where a select element is populated dynamically. The parameter that needs to be passed is customerProfile.id. I want to find this id in the select options and have it selected by default. How can I achiev ...

Javascript functions correctly when the HTML file is opened locally, however, it encounters issues when accessed through an http-server

My HTML file includes an embedded web widget from tradingview.com with the following code: <!-- TradingView Widget BEGIN --> <span id="tradingview-copyright"><a ref="nofollow noopener" target="_blank" href="http://www.tradingview.com" style ...

What methods can be used to accurately display the data type with TypeOf()?

When working with the following code: const data = Observable.from([{name: 'Alice', age: 25}, {name: 'Bob', age: 35}]); console.log(typeof(data)); The type is displayed as Object(). Is there a way to obtain more specific information? ...

Executing a Ruby method on a server using JavaScript - A guide

I'm facing a seemingly simple issue that I can't seem to find a clear solution for anywhere. Essentially, I have a JavaScript application hosted on a server that requires passing information between the JS app and a Rails-built server. The proces ...

Problem occurs when tab links vanish after clicking on another part of the website

Exploring the world of Javascript as a newcomer has been quite an adventure, but I've encountered a hurdle with tab links on my website. Everything seems to be working fine – the links cycle through and display the correct content. However, when it ...

How can I create a real-time page update using node.js?

I am completely new to node.js, but my main goal in learning this language is to achieve a specific task. I want to create a webpage where the content within a designated "div" can be swapped dynamically for users currently viewing the page. For example, ...

I'm curious if it is possible to retrieve the dates of actions on websites using Selenium with Python

Is there a way to retrieve the date of data, like the date of comments, using HTML codes? I need assistance on how to achieve this through selenium in Python. Can Jquery be used as a solution? ...

Is there a way to retrieve an array generated within a JavaScript loop?

I've been working on retrieving column values from a database and storing them in an array, but I keep getting an empty array as the result. function FetchData(query, db) { var resultArray = new Array(); db.transaction(function(tx) { tx.executeSq ...

Struggling with getting React to successfully fetch data from an Express API. Any suggestions on how

I am having trouble with my fetch call to the express API. Even though I receive a response status of 200, I am still getting the index.html instead of the JSON data I need. Here is an overview of my setup: package.json "version": "1.0.0&qu ...

Directives for conditions if Internet Explorer is greater than or equal to 9, or if it is not

Embarking on a new project, I find myself in the unfortunate position of having to support IE7 & IE9. However, my goal is to eventually phase out IE7 support smoothly. Ideally, I aim to utilize the latest versions of libraries wherever possible. < ...

The $resource.query function will now return an array of characters instead of a single string when splitting strings

Recently, I've been working on utilizing an Angular $resource in my project. Here's a snippet of the code: angular.module('app') .factory('data', function ($resource) { var Con = $resource('/api/data', {}, { ...

Having trouble getting my soundboard to work properly on mobile devices

I recently created a soundboard using HTML5, CSS3, and JavaScript. While the audio plays back perfectly on my computer when I click the buttons, I encounter an issue when trying to use it on a smartphone. <!DOCTYPE html> <html lang="en"> <h ...

Learning to implement a sliding effect on tab bar button click using Angular

When a user clicks on any tab button, I am using the transition effect "slide" to display the content. I have successfully implemented this in jQuery Mobile and you can see it in action in this fiddle: http://jsfiddle.net/ezanker/o9foej5L/1/. Now, I tried ...

Getting undefined while trying to iterate through data on a next js page using getStaticProps. What could be causing this issue?

Encountering difficulties while trying to output the page meta data in next.js when I execute: npm run build An error is thrown with the following message: Error occurred prerendering page "/blog/[...slug]". Read more: https://err.sh/next.js/pre ...