我有以下情况。我想从服务器加载文件 A,该服务器又会尝试加载文件 A1、A2、A3、... An 并且每个文件 A[1-n] 将依次加载其他文件,这可以继续;但它已经结束了。我想使用延迟对象来设置它(以免使用 async: false 挂起浏览器),但是加载和解析文件的递归让我对如何设置对象感到困惑。此外,还要求必须完成最高递归深度级别 (l),然后我才能继续级别 (l-1)。对于没有递归的情况,此代码有效,但递归情况使我无法理解。
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);