1

I need to load JSON data from a server using JavaScript and/or jQuery with an AJAX request.

I have several other scripts on the same page load that will need to access this JSON data after it is loaded so it is important that it is loaded before my other code runs.

I would like to utilize and use the newer Promises and Deferred Objects

Also this question and example code shows 1 instnce of loading JSON data fro my app but in the final result I will duplicate this to load 3-4 different sets of JSON data from 3-4 AJAX requests. So it is important to get this right so that all my requests can use the same code.

A little background on the data and its use might help to understand my goal a little better...

I am building a Project Management app which has a main core JavaScript object/file. I then have sub-module JavaScript object/files which work together with the core file.

Some of these include:

  1. Core ProjectManagement.js
  2. ProjectManagement.User.module.js
  3. ProjectManagement.Milestones.module.js
  4. ProjectManagement.Tags.module.js
  5. ProjectManagement.Tasks.module.js
  6. ProjectManagement.Files.module.js
  7. ProjectManagement.Activity.module.js

Now in my core PM JavaScript file I will need access to a userlist JSON object. THe userlist should be loaded on page load with 1 AJAX request made from the ProjectManagement.User.module.js object/file and then cached the JSON result to a variable inside the ProjectManagement.js object/file.

The next time that nany of the sub-module JavaScript code needs to access the userlist JSON, it will simply get the data from the cached variable instead of making an additional AJAX request to get the data over and over for each sub-module.

This same situation applies to all the related data such as Milestones, Tags, ACL Permissions, and more.

For this reason I feel the JavaScript Promises and Deferred objects are a good route to go instead of callback functions. I need to load all these JSON objects from multiple AJAX requests and have them all load before all my sub-module JS code starts calling for them and causing problems.

In my attempt to use Promises and Deferred objects, this is what I have from the code below...

  1. var deferredLoadTaskObject = $.Deferred();
  2. On AJAX success I call the resolve() function of the deferred object deferredLoadTaskObject.resolve();
  3. On AJAX failure I call the reject() function of the deferred object deferredLoadTaskObject.reject();

Now to be honest, I am not sure that I even need to do the above calls. I know that all jQuery AJAX requests are in themselves a Promise so this code above might be simply doing the same thing over again 2 times?

I much prefer the explicit calls that the code above makes as it seems more cut and dry to show what it is doing. However as mentioned I am not sure that it is required or not?

Am I doing it all wrong?

My code below shows a simplified/cleaned up version of 1 of my AJAX request which uses the Promise/Deferred code from above.

I have a specific function that has 1 single job which is to make the AJAX request and return the result. I would like to continue this approach as it is clean and easy to understand and follow.

I can simply have a function like ajaxLoadTaskData(task_id) for each of my data sets that I need (milestones, users, tags, etc...).

I then have var taskDataAjax = ajaxLoadTaskData(task_id); which assigns the AJAX request to the var taskDataAjax and I then can call taskDataAjax.done(), taskDataAjax.fail(), and taskDataAjax.always() on it which inside of each of these I can then call deferredLoadTaskObject.resolve() and deferredLoadTaskObject.reject() to satisfy the Promise/Deferred Objects


Short Summary Version...

If you can't be bothered to read above fully...

I simply need help in making sure I am using the Promise/Deferred Objects correctly make my AJAX requests which will in the end be making several different AJAX requests and on there completion will assign data to variables to be used among several JavaScript sub-modules/objects/files in my large JS Application.

If I am doing it wrong, please kindly provide some help in making it correct

One area of concern is my use of calling var deferredLoadTaskObject = $.Deferred(); and then calling deferredLoadTaskObject.resolve() and deferredLoadTaskObject.reject() inside the AJAX response callbacks.

I am not sure if this is correct use or if I should not be calling these since jQuery AJAX request are by default already a Promise of some sort.


JavaScript function that makes AJAX request to load JSON data and returns it

ajaxLoadTaskData: function(task_id) {
    return $.ajax({
      type: 'POST',
      async: true,
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      url: getTaskRecordUrl,
      data: {
        action: 'load-task-record',
        task_id: task_id
      },
    });
},

Testing use of Promises and Deferred Objects

var deferredLoadTaskObject = $.Deferred();

JavaScript which calls the above function for the AJAX request...

// Get Task Data from AJAX Request
var taskDataAjax = ajaxLoadTaskData(task_id);

taskDataAjax.done(function(response) {

        // JSON response from AJAX request
        var taskRecordJson = response;

        deferredLoadTaskObject.resolve();
});


taskDataAjax.fail(function(response) {
    // AJAX request failed
    console.log('response', 'response');

    deferredLoadTaskObject.reject();
});


taskDataAjax.always(function(response) {

});

JasonDavis
  • 48,204
  • 100
  • 318
  • 537
  • Not necessary to create additional jQuery deferred object ? `$.ajax()` returns jQuery promise object . If returned promise value from `$.ajax()` is to be changed , try substituting `.then()` for `.done()` , see http://stackoverflow.com/questions/5436327/jquery-deferreds-and-promises-then-vs-done? – guest271314 Oct 17 '15 at 02:53

0 Answers0