我必须搜索可能有几十万行的单词索引表。我可以通过向搜索传递文档列表来限制搜索。在许多文档中搜索单词的请求返回速度非常慢。因此……为了改进用户体验,我们将请求分为多组文档。因此,如果用户要求搜索90个文档,并且块大小为每个查询10个文档,那么我们将发出90/10=9个独立的$.ajax()调用。我们希望结果按照发送的顺序来。
我们实现了这种递归:
var SearchFunction = function () {
$.ajax(/* ... */);
}
var RecursiveSearch = function () {
var deferred = $.Deferred();
if (arrTransSearch.length > 0) {
deferred = SearchDocuments(arrTransSearch.shift());
}
else {
deferred.reject();
}
return deferred.promise().then(RecursiveSearch);
}
if (arrTransSearch.length > 1) {
RecursiveSearch().fail(SomeFunction);
}
var SomeFunction = function () {
alert("Failed. Yes!");
}
调试代码时,deferred.reject()
不会更改deferred.promise()
的状态。也就是说,当下一行
return deferred.promise().then(RecursiveSearch)
执行时,它只是循环回递归函数,而不是退出递归并落入
RecursiveSearch().fail(SomeFunction);
重要提示:
我使用的是jQuery-1.7.1。我在JSFiddle中运行了类似的递归(谢谢Beeetroot Beetroot),它在jQuery-1.7.2上失败,而在jQuery-2.1.0中运行时没有问题。
关于如何让递归在jQuery-1.7.1中工作,有什么想法吗?
此处在"集合混乱"标题下提供了一个部分覆盖您所需内容的模式。实际上,您需要的不仅仅是这些,因为您希望以块(组)的形式处理您的文档引用列表。
代码将是这样的:
$(function() {
//General ajax options for searching a document group
var ajaxOptions = {
url: '...',
type: 'POST',
//data: ... //added dynamically
dataType: 'JSON',
// etc.
};
//
function searchDocumentsInGroups(arr, n) {
//Pre-process arr to create an array of arrays, where each inner array is a group of document references
var groups = [];
$.each(arr, function (i) {
if (!(i % n)) groups.push(arr.slice(i, i + n));
});
//Ajax serializer (from the Collection Kerfuffle reference)
return groups.reduce(function (promise, group) {
return promise.then(function () {
return $.ajax($.extend({}, ajaxOptions, {
data: JSON.stringify(group);//or whatever, compatible with the server-side script
})).then(function (groupResults) {
//display groupResults here
});
});
}, $.when(0));
}
// data
var myDocumentArray = [ 'doc1', 'doc2', 'doc3', 'doc4', 'etc.' ], //Your array of 90 document references.
groupSize = 10; //Number of documents per "chunk".
// Event handler to kick off the process.
$("#searchDocuments").on('click', function () {
// display "in progress" message or spinner here
searchDocumentsInGroups(myDocumentArray, groupSize).then(function () {
// display "complete" message or hide spinner here
});
});
});
您还需要Array.prototype.reduce的Polyfill,因为.reduce依赖于以上版本,而较旧的浏览器(ECMAScript5之前)没有它。
if ( 'function' !== typeof Array.prototype.reduce ) {
Array.prototype.reduce = function( callback /*, initialValue*/ ) {
'use strict';
if ( null === this || 'undefined' === typeof this ) {
throw new TypeError(
'Array.prototype.reduce called on null or undefined' );
}
if ( 'function' !== typeof callback ) {
throw new TypeError( callback + ' is not a function' );
}
var t = Object( this ), len = t.length >>> 0, k = 0, value;
if ( arguments.length >= 2 ) {
value = arguments[1];
} else {
while ( k < len && ! k in t ) k++;
if ( k >= len )
throw new TypeError('Reduce of empty array with no initial value');
value = t[ k++ ];
}
for ( ; k < len ; k++ ) {
if ( k in t ) {
value = callback( value, t[k], k, t );
}
}
return value;
};
}
所有这些都未经测试,但我最近在这里回答了一个类似的问题,并附上了一个小提琴链接。
事实证明,在jQuery-1.8之前,用一个参数调用$.then()
相当于调用$.then(successFunction, successFunction)
。由于我使用的是jQuery-1.7.1,被拒绝的promise仍然会调用递归。