jf328
jf328

Reputation: 7351

jQuery best way to make sure one function is run before all others

I would like to read a text file and get its content to a variable and use that variable everywhere.

var latest_date = "";
$.get('/data/latest_data.txt', function(data) {
  latest_date = data; // eg "20180102"
}, 'text');

// and lots of similar functions like this
$(function() {
  $.getJSON('../data/' + latest_date + '/overview.json', function(data){
    $('#overview').DataTable(data);
  });
});

However, other functions will run before latest_date variable gets its correct value. How can I make sure the $.get function runs before anything else?

It's similar to this question How should I call 3 functions in order to execute them one after the other? But I have loads of functions. I can't put all of them as the callback of the initial function. I'm also reluctant to add timeOut to all my functions. Is there a better way?

Upvotes: 0

Views: 103

Answers (2)

Sinan Guclu
Sinan Guclu

Reputation: 1087

You could use an event and then attach multiple listeners to call the functions you need to call once the file has loaded:

Dispatch event on the window object when the first request completes:

var latest_date = "";
$.get('/data/latest_data.txt', function(data) {
  latest_date = data; // eg "20180102"
   window.dispatchEvent(new Event('content:loaded'))
}, 'text');

Listen for the event to call the other gets.

window.addEventListener('content:loaded', function() {
   $.getJSON('../data/' + latest_date + '/overview.json', function(data){
      $('#overview').DataTable(data);
   });
});

You could also send the latest_date variable in the event if you want to avoid using global variables:

window.dispatchEvent(new CustomEvent('content:loaded', {
    detail: {
        latest_date: 'date',
    }
}));

window.addEventListener('content:loaded', function(e) {
    console.log(e.detail.latest_date); // = 'date'
});

Read more about Events here

Upvotes: 0

Ippei Tanaka
Ippei Tanaka

Reputation: 149

You can use a Promise object on the jqXHR returned by the get method. For example:

var promise = $.get('/data/latest_data.txt', 'text').promise();

promise.then(function (latest_date) {
    $.getJSON('../data/' + latest_date + '/overview.json', function (data) {
        $('#overview').DataTable(data);
    });
});

Upvotes: 3

Related Questions