Stupid.Fat.Cat
Stupid.Fat.Cat

Reputation: 11295

jquery handling recursive ajax calls, how to tell the browser it's done

I have an endpoint that returns me a next token if there are more things to fetch, and the code that I'm writing to fetch it looks like so:

        function get_all_entities(campaign_id, page){
            get_campaign_entities(campaign['id'], page)
                .success(function(data){
                    if (data['next']){
                        console.log(data['next'])
                        get_all_entities(campaign_id, page+1)
                    }
                })
        }

        get_all_entities(campaign['id'], 1)

Now, while this works, the function that actually calls it get_all_entities(campaign['id'], 1) has no way on knowing when everything is done. I've tried adding a while loop like so but it crashes my browser (everything freezes up)

        function get_all_entities(campaign_id, page){
            all_done = false
            get_campaign_entities(campaign['id'], page)
                .success(function(data){
                    if (data['next']){
                        console.log(data['next'])
                        get_all_entities(campaign_id, page+1)
                    }
                    else{
                        all_done = true
                    }
                })
            while (!all_done){
                setTimeout(function(){
                }, 2000);
            }
            return all_done
        }

I've also tried returning get_campaign_entities and use the done callback but the done callback only works for the first call.

Upvotes: 1

Views: 523

Answers (1)

SimpleJ
SimpleJ

Reputation: 14768

You could add a callback argument:

function get_all_entities(campaign_id, page, callback) {
  get_campaign_entities(campaign['id'], page)
    .success(function(data) {
      if (data['next']) {
        console.log(data['next'])
        get_all_entities(campaign_id, page + 1, callback)
      } else {
        callback();
      }
    })
}

get_all_entities(campaign['id'], 1, () => {
  console.log('Done!');
});

Upvotes: 1

Related Questions