I have the following situation. I would like to load file A from a server which in turn will try to load files A1, A2, A3, ... An and each file A[1-n] will in turn load other files and this can keep going; but there is an end to it. I would like to set it up using deferred objects (so as to not hang the browser by using async: false) but the recursion of loading and parsing the files confuses me on how to set up the objects. In addition there is a requirement that the highest recursion depth level (l) must finish before I can continue with level (l-1). For the case where there is no recursion this code works but the recursive case eludes me.
var loadFile = function (index, url, scope, callback) {
    $.ajax ({url: url, type: 'GET', dataType: 'text'})
    .done (function (responseText) {
        // store response in array
        scope.requests[index] = responseText;
    })
    .fail (function (xhr, status, error) {
        scope.requests[index] = 'error';
    })
    .always (function (responseText) {
        // loop through entire response array from the beginning
        for (var j = 0; j < scope.requests.length; j++)
        {
            if (scope.requests[j] === 'unprocessed') return;
            else if (scope.requests[j] === 'error')
                scope.requests[j] = 'done';
            else if (scope.requests[j] !== 'done')
            {
                parseFile (scope.requests[j], scope, callback);
                scope.requests[j] = 'done';
            }
        }
        // if all are done then reset the array and run the callback
        delete scope.requests;
        if (callback) callback();
    });
}
var parseFile = function (responseText, scope, callback) {
    var lines = responseText.split("\n");
    for (var l = 0; l < lines.length; l++) {
        var line = lines[l];
        line = line.replace (/^\s+/, ''); // remove leading white space
        if (line.charAt(0) === '1') // file reference
        {
            var attrs = line.split (/\s+/);
            // the file will exist in any of the paths in pathList
            for (var i = 0; i < scope.pathList.length; i++) {
                scope.requests.push ('unprocessed');
                loadFile (++index, scope.pathList[i] + attrs[14], scope, callback);
            }
        }
    }
}
var index = 0;
var this.requests = [];
this.requests.push ('unprocessed');
loadFile (index, fileAi, this, callback);
 
     
     
    