我想創建一個函數隊列來調用返回自動完成結果。其中一些是我從$ .getJSON調用構建自己的函數,有些是由外部開發人員使用what's specified for jQuery UI autocomplete提供給我的。混合回調函數和jQuery延期隊列
例如,這裏提供了一個假的。我不知道前面,如果是真正的異步或什麼時候會調用回調:
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謝謝,但我不知道如何將它轉換爲延遲,因爲我不控制它的定義(它傳遞給我) –