次のような状況があります。サーバーからファイル A をロードしたいのですが、サーバーはファイル A1、A2、A3、... An をロードしようとし、各ファイル A[1-n] は他のファイルをロードし、これは続行できます。しかし、それには終わりがあります。(async: false を使用してブラウザーがハングしないように) 遅延オブジェクトを使用してセットアップしたいのですが、ファイルの読み込みと解析の再帰により、オブジェクトのセットアップ方法がわかりません。さらに、レベル (l-1) を続行する前に、最高の再帰深度レベル (l) を終了する必要があります。再帰がない場合、このコードは機能しますが、再帰的な場合はわかりません。
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);