Working with jQuery.ajax Function Calls in Array Filter Operations with Javascript

My knowledge of AJAX calls is limited, so I am unsure about how they interact with array filtering using A.filter(). The array in question is used to populate a template synchronously.

// An event triggers a function to filter a list on the page.
// The function then calls filterArray(arrayList, objFilters)

async_fetch: function(string)
{
  // Uses $.ajax() to retrieve a JSON array
  var deferred = $.Deferred();

  $.ajax({
    url: ...,
    dataType: "json",
    success: function(data) {
      var response = data;
      deferred.resolve(data);
    },
    error: function(data)
    {
      //...
      deferred.reject(msg);
    }
  });
  return deferred;
};

filterArray: function(list, filters)
{
  var filteredList = list.filter(function(item) {
    for(var key in filters) {
      // Actions for multiple filters to compare against...
      else if(key == 'FILTER_X') {
        var data = async_fetch(item.name);
        // Using data to make a determination where true means excluding the item from the filtered list
        if(determination)
          return false;
      }
    }
  };
  return filteredList;
};

// Results of filterArray() are sent to a template within Backbone 
//   to update an HTML segment on the page.

Will the call to filter wait synchronously for the AJAX call to complete? Will the list be filtered and returned without waiting for the AJAX call to finish, requiring the AJAX call to integrate into the filtered list later? Should I create a non-async version of async_fetch() instead?

Answer №1

To handle the call, make sure to use either .then() or .done() like this: ....

 async_fetch(item.name).then(function(data){
        if (data.determination)
          // do something
    })

....

Answer №2

Greetings! You can complete the promise once you have filtered the data. Here's an example:

$(document).ready(function(){
  function retrieveFilteredData(url)
{
  // Using $.ajax() to fetch a JSON array
  var deferred = $.Deferred();

  $.ajax({
    url: url,
    dataType: "json",
    success: function(data) {
      var filteredData = filterArray(data);
      deferred.resolve(filteredData);
    },
    error: function(data)
    {
      //...
      deferred.reject(msg);
    }
  });
  return deferred;
};

 function filterArray(data)
{
  var filteredList = data.filter(function(item) {
   //add your filtering logic here
    })
  return filteredList;
}

retrieveFilteredData(url).then(function(response){
  //you will receive the filtered data here
  console.log(response);
}) 
});

Answer №3

To implement this functionality using async/await, follow the instructions below:

const filterItems = async function (items, filters) {
    var filteredListPromise = items.filter(async function (item) {
        for (var key in filters) {
            // Perform actions for each filter to compare against...
            if (key === 'FILTER_X') {
                return checkItemName(item.name);
            }
            else {
                // Handle other filters
            }
        }
    });
    return Promise.all(filteredListPromise);
};

async function checkItemName(name) {
    let data = await fetchDataAsync(name);
    return determineCondition ? true : false; // Add your custom logic here
}

// Usage example:

filterItems(items, appliedFilters).then(result => {
    console.log(result);
}).catch(error => {
    console.log(error);
})

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

Is there a way to transform a large gltf file into jsx format?

I recently created a 3D scene in Blender and wanted to incorporate it into my React Three Fiber project. However, after exporting the scene to glTF format, I discovered that the file contained around 300k lines. The strange thing is that the file works per ...

A routing error was encountered when attempting to process a PUT request for an ajax call in the ActionController

Just checking in to see how you're doing. I want to initiate an ajax call on _questions_form. The process is functioning correctly without the remote: true option, but the issue arises when using actioncable, as the data disappears after form submiss ...

What is the best method to retrieve the nested value in this JavaScript/HTML code?

Can anyone help me extract the value "Yes, I am a Speaker" from this code using Javascript DOM element with getElementById? The challenge is that the value is nested inside a list element without any specific attributes. Each block of code has a unique l ...

Error [ERR_UNSUPPORTED_DIR_IMPORT]: Nodejs App cannot be started locally due to a directory import issue

My journey to deploy my app on Heroku has hit a roadblock. The import statements, like import cors from 'cors', are causing the app to fail in production with the "Cannot Load ES6 Modules in Common JS" error. Interestingly, everything runs smooth ...

Organizing Firestore data into structured JSON format

For my database collection, I am utilizing a cloud function to download it as a JSON file. Here is the code snippet: exports.csvJsonReport = functions.https.onRequest((request, response) => { const db = admin.firestore() const userAnswers = db.col ...

Trigger a Redux action with the following action as the payload in order to display a Material UI snackbar or dialog

Currently, my project involves using React along with Redux and Material UI to develop a web application. The web app consists of numerous pages and components. It is common practice to have a snackbar or dialog interact directly with the user's actio ...

Getting the string value from query parameters can be achieved by accessing the parameters and

Currently, I am attempting to retrieve the string value stored within a class-based object variable named question5. The way I am trying to access this variable on the front-end is shown below. axios.get("http://localhost:3001/users/questionaire/?getq ...

Showing content from a JavaScript variable once a button has been clicked

Imagine you are using express.js and have a JavaScript variable embedded in an ejs file like this: <%= someVariable %> How can you display the value from this variable on the same page, for instance within a bootstrap modal element (check out https: ...

Conceal a div using jQuery within an AJAX function

Utilizing AJAX, I am attempting to substitute the text "Follow" with a spinner and then exhibit the success message. The HTML code within a loop appears as follows: <div id="author-id-3" class="km-follow-me"> <div cl ...

What is the process for sorting Google Map markers with AngularJS?

.controller('MapCtrl', ['$scope', '$http', '$location', '$window', '$filter', '$ionicLoading', '$compile','$timeout','$ionicPopup', function ...

"Use jquerytools to create a dynamic play/pause button functionality for scrollable content

Greetings! I am currently working on creating a slide using Jquerytools. Here are some helpful links for reference: To view the gallery demonstration, please visit: For information on autoscroll functionality, check out: If you'd like to see my cod ...

(JS) utilizing an external .js function by using the <script> tag

Looking to execute the function cookiefix() from main.js, which is linked at the bottom of my HTML file. echo '<body>'; if(!isset($_COOKIE['clicked'])) { if(!isset($_COOKIE['count'])) { echo '<script type="text/ ...

Adding and Removing Attributes from Elements in AngularJS: A Step-by-Step Guide

<input name="name" type="text" ng-model="numbers" mandatory> Is there a way to dynamically remove and add the "mandatory" class in Angular JS? Please note that "mandatory" is a custom class that I have implemented. Thank you. ...

How to retrieve plain text data from a jQuery ajax call to a PHP server

Having trouble getting my ajax request to a php page to return plain text. Here's the code snippet: $.ajax({ type: 'GET', url: '/shipping/test.php', cache: false, dataType: 'text', ...

Conceal all div elements except for displaying the initial two

Can an entire div be hidden with only the first 2 entities visible? <div class="inline-edit-col"> <span class="title inline-edit-categories-label">Brands</span> <ul class="cat-checklist product_brand-checklist"> < ...

Is it advisable to save the text that is utilized in a label?

My journey into web development is just beginning, and I am currently using React JS for my front end development. I have a component that dynamically renders labels based on JSON data, This is how the JSON data looks: data:{ name:"test123" ...

Scrolling up or down in an HTML webpage using a script

Seeking a code snippet for my website that will allow me to achieve the following functionality: Upon clicking on text_head1, a list of lines should scroll down. Subsequently, when I click on text_head2, the previous list should scroll up while the new l ...

The Chrome Keyboard on Android seamlessly passes words to the next input field when the focus changes in JavaScript

When using two input fields, pressing the enter key on the first field in Chrome (49) on Android (6.0.1) carries over the last word typed to the new input due to the right-bottom button on the standard keyboard. Is there a way to prevent this behavior or a ...

Send the form data from a modal controller in AngularJS to an ng-controller outside of the modal

There seems to be a confusion with the functionality not working as expected: In my Angular application, I have a main page with an ng-controller named "SearchCtrl" that handles sending search requests to a webserver. app.controller('SearchCtrl&apos ...

retrieve the webpage hosted on the server

Seeking to develop a website where users can input a website URL and have it loaded from the server hosting the HTML page, rather than from the user's computer as iframe does by default. I've experimented with various techniques but all seem to l ...