Pregunta

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);
}));  
¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top