使用AJAX设置和返回变量的JavaScript模块

时间:2014-05-15 15:28:18

标签: javascript jquery ajax

我试图编写一个模块来进行两次AJAX调用并将变量设置为这些调用的结果。我希望能够访问myModule.firstCall这些调用的结果,并获得AJAX调用的结果,而不是承诺。

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);
}));  

1 个答案:

答案 0 :(得分:1)

不,你cannot return the result from an asynchronous call

将它们分配给全局(或更高范围)变量(例如示例中的subFolderDatarootData)是可能的,但没有意义,因为您不知道值何时会可用。

存储值的承诺,例如您的ajaxModule.subFolderFileajaxModule. rootFile,并且在需要访问数据时始终合并它们是可行的方法。