-2

I'm trying to write a module that makes two AJAX calls and sets variables to the results of those calls. I'd like to be able to access the results of those calls like myModule.firstCall and get the result of the AJAX call and not the promise.

var ajaxModule = (function () {
    var subFolderData = {},
        rootData = {};

    var subFolderFile = function () {
        return $.ajax({
            url: 'Content/testData.json',
            dataType: 'json'
        });
    }
    var rootFile = function () {
            return $.ajax({
                url: 'testDataRoot.json',
                dataType: 'json'
            });
        }
        //only returning promise here, how to return $.when the call is done?
    return {
        rootFile: rootFile().done(function (data) {
            subFolderData = data;
        }),
        subFolderFile: subFolderFile().done(function (data) {
            rootData = data;
        })
    }
})();
//this prints out the dat as expected, but can I store the results in a variable
//to be accessed like ajaxModule.rootFile?
console.log(ajaxModule.rootFile.done(function (data) {
    console.log(data);
}));  
wootscootinboogie
  • 8,461
  • 33
  • 112
  • 197

1 Answers1

1

No, you cannot return the result from an asynchronous call.

Assigning them to a global (or higher-scope) variable, such as subFolderData or rootData in your example, is possible, but does not make sense because you do not know when the value will be available.

Storing the promises for the values, like your ajaxModule.subFolderFile and ajaxModule. rootFile, and always incorporating them when needing to access the data, is the way to go.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • so, if i want to store the results of an AJAX call and use it in multiple places in my application i'll always have to do something like `myVar.done(callback)?` i was hoping there might be prettier syntax than that – wootscootinboogie May 15 '14 at 16:08
  • 1
    Yes, you always need a callback. However, a) if your whole application depends on the results you can put the whole code in the callback, where you access `data` multiple times b) you've got the full power of composing promises available – Bergi May 15 '14 at 16:15