kd1978
kd1978

Reputation: 511

Run ajax request until it returns results

I currently rely on a simple ajax call to fetch some data from our query service api. It is unfortunately not the most robust api and can at times return an empty result set. As such, I want to retry the ajax call until resultSet.length > 0.

I could use setTimeOut and break the loop if I find results, but it seems like an inelegant solution, especially as the time to completion is anywhere between 1s and 6s. I currently have the following, but it doesn't seem to break the loop when needed, and remains inelegant. Any help would be appreciated!

var resultSet = 0;

function fetchQueryData(query, time, iter) {
  (function myLoop(i){
    if (i == iter) {
      fetchData(resultSet, dataset, query);
    } else {
      setTimeout(function(){
       if (resultSet == 0) {
         fetchData(resultSet, dataset, query); 
       }
       if (--i) myLoop(i);
     }, time)
    }
  })(iter);
}

fetchQueryData('select * from table', 6000, 5);

function fetchData(resultSet, dataset, query) {
  var dataString = 'query=' + encodeURIComponent(query);

  $.ajax({
    type : "POST",
    data: dataString,
    url : "/queryapi",
    success: function(json) {
      var data = [];
      var schema = json.data.schema;
      var rows = json.data.rows;

      if (typeof schema != 'undefined') {
         resultSet = 1;
         for (var i = 0; i < rows.length; i++) {
           var obj = {};
           for (var j = 0; j < schema.length; j++) {
             obj[schema[j]['name']] = rows[i][j];
           }
           data.push(obj);
         }
      }  
  });
}

Upvotes: 1

Views: 90

Answers (1)

j6m8
j6m8

Reputation: 2399

Instead of using a setTimeout, wrap the request in a function, and call that same function in the success callback of the request if the returned set is empty.

This will prevent you from sending more than one request to your API at a time, and will also terminate as soon as you get back a satisfactory response.

(In short, you're using recursion instead of an explicit loop.)

Upvotes: 2

Related Questions