Oliver.L
Oliver.L

Reputation: 11

Sequentially execute two functions with jQuery in for loops

I'm pretty new to Javascript. Please don't make it too harsh :)

I have two functions, both of which involve executing jQuery requests within for loops. For example,

function a(n,locations) {
  for (var i = 0; i < n; i ++) {
    $.ajax({
      url: 'https://geocoder.cit.api.here.com/6.2/geocode.json',
      type: 'GET',
      dataType: 'jsonp',
      jsonp: 'jsoncallback',
      data: {
        searchtext: input,
        app_id: APP_ID,
        app_code: APP_CODE,
      },
      success: function (data) {
        handleData(data,locations);
      }
   });
 }

The handleData() function would make changes to the empty array locations from the jQuery data. My function b(m) is of similar format but would use the updated locations as input.

Now, I have a c(n,m) in which I would like execute a() and b() sequentially:

function c(n,m) {
  var locations = [];
  a(n,locations);
  b(m,locations);
}

From previous answers I understand that sequentially executing functions involving jQuery calls can be achieved by using promises (such as .then). However, this solution is only applicable when a(n) returns a promise, which is not achievable under the for-loop structure. Could you please share your insights on how to solve this issue? Thanks in advance for the help.

Upvotes: 1

Views: 114

Answers (1)

notphilphil
notphilphil

Reputation: 385

I would suggest recursion instead of your for loop. For example, you can call the function recursionExample like this,

function a(n) { 
  return new Promise ((resolve, reject) {
    (function recursionExample(a) { 
      if (a === n) {
          resolve;
      } else {
          $.ajax({ url: 'https://geocoder.cit.api.here.com/6.2/geocode.json', 
          type: 'GET', 
          dataType: 'jsonp', 
          jsonp: 'jsoncallback', 
          data: { 
              searchtext: input, 
              app_id: APP_ID, 
              app_code: APP_CODE, 
          }, 
          success: function(data) { 
            handleData(data);
            recursionExample(a + 1);
          } 
        }); 
      }
    })(0);
  });
}

This will then allow you to use the promise and .then functions. Like so...

function c(n,m) { 
    var locations = []; 
    a(n,locations)
    .then (function() {
        b(m,locations); 
    });
}

Upvotes: 1

Related Questions