简体   繁体   中英

Javascript: How to Handle jQuery.ajax Function Calls within an Array Filter Operation?

I'm not familiar enough with AJAX calls to know how this does or doesn't work. If I have an array A and I'm using A.filter() on it, how will AJAX calls within filter work? The array is being used to populate a template, all synchronously I believe.

// Event calls function to filter list on page.
// Function calls filterArray(arrayList, objFilters)

async_fetch: function(string)
{
  // Utilizes $.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 each of multiple filters to compare against...
      else if(key == 'FILTER_X') {
        var data = async_fetch(item.name);
        // Use data to arrive at a determination, where true means I don't want to include this item in the filtered list
        if(determination)
          return false;
      }
    }
  };
  return filteredList;
};

// Results of filterArray() are passed along to a template within Backbone 
//   to redraw a segment of HTML on the page.

Will the call to filter just wait synchronously for the AJAX call to finish? Will the list get filtered otherwise and returned, and the AJAX call have to hook into the filtered list, and essentially finish the filtering later? Should I just build a version of async_fetch() that isn't async?

You will need to .then() or .done() the call, eg ....

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

....

Hi you can resolve the promise after your filtering the data. example like, hope this help you.

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

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

 function filterArray(data)
{
  var filteredList = data.filter(function(item) {
   //filter whatever you want
    })
  return filteredList;
}

async_fetch(url).then(function(response){
  //now you will get the filterd data
  console.log(response);
}) 
});

You can do this with help of async/await as below:-

const filterArray = async function (list, filters) {
    var filteredListPromise = list.filter(async function (item) {
        for (var key in filters) {
            // Actions for each of multiple filters to compare against...
            if (key == 'FILTER_X') {
                return arriveAtDetermination(item.name);
            }
            else {
                //other filters
            }
        }
    });
    return Promise.all(filteredListPromise);
};

async function arriveAtDetermination(name) {
    let data = await async_fetch(name);
    return determination ? true : false;//your logic
}

//Now you can filter like

filterArray(list, filters).then(result => {
    console.log(result);
}).catch(err => {
    console.log(err);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM