【发布时间】:2013-04-01 19:30:31
【问题描述】:
我正在尝试创建一个要调用的函数队列以返回自动完成结果。其中一些是我通过 $.getJSON 调用自己构建的函数,还有一些是由外部开发人员使用what's specified for jQuery UI autocomplete 提供给我的。
例如,这里提供了一个假的。我不知道它是否真正异步或何时可能调用回调:
var providedFunction = function(search, response) {
setTimeout(function() {
var arr = ['One', 'Two', 'Demo Custom'];
response($.grep(arr, function (s) { return s.indexOf(search) === 0; }));
},5000);
};
然后我想将它与其他一些 $.getJSON 调用结合起来,直到整个列表完成后才继续:
var searchTerm = "Demo";
var allResults = [];
var functionQueue = [];
functionQueue.push(
$.getJSON( 'http://ws.geonames.org/searchJSON?featureClass=P&style=short&maxRows=50&name_startsWith=' + searchTerm)
.success( function(data) {
$.each(data.geonames, function(i,d) {
allResults.push(d.name); });
})
);
functionQueue.push(
providedFunction(searchTerm, function(data) {
allResults.push.apply(allResults, data);
})
);
// wait for all asyc functions to have added their results,
$.when.apply($, functionQueue).done(function() {
console.log(allResults.length, allResults);
});
问题在于 $.when 不等待提供的函数完成。它会在所有 $.getJSON 调用完成后立即返回。很明显,我没有正确连接提供的功能,但我不知道该怎么做。
【问题讨论】:
-
providedFunction不是延迟对象,因此$.when假定它会立即解决。 -
@KevinB 谢谢,但我不知道如何将其转换为延迟,因为我无法控制它的定义(它已传递给我)
标签: javascript jquery jquery-ui jquery-ui-autocomplete jquery-deferred