我正在尝试创建一个要调用的函数队列以返回自动完成结果。其中一些是我通过 $.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 调用完成,它就会返回。很明显,我没有正确连接所提供的功能,但我不知道如何做到这一点。
最佳答案
如果您决定使用 $.when,您将需要创建一个延迟数组,这样您就可以像这样调用提供的函数:
functionQueue.push( (function(){
var df = new $.Deferred();
providedFunction(searchTerm, function(data) {
allResults.push.apply(allResults, data);
df.resolve();
})
return df;
})()
);
当然,如果您真的很喜欢,您可以使用这个方便的实用程序将基于回调的 API 转换为基于 Promise/deferred 的 API:
function castAPItoDeferred(origFunction){
return function(){
var df = new $.Deferred(),
args = Array.prototype.slice.call(arguments, 0);
// assume that the API assumes the last arg is the callback
args.push(function(result){
df.resolve(result);
});
try {
origFunction.apply(null, args);
} catch(e) {
df.reject(e);
}
return df;
}
}
这会让你做一些像这样的好事:
providedFunctionAsDeferred = castAPItoDeferred(providedFunction);
functionQueue.push(
providedFunctionAsDeferred(searchTerm)
.success( function(data) {
allResults.push.apply(allResults, data);
})
);
最后一个警告 - 如果您确实选择第二条路线,请记住在对象上调用 API 函数(例如 myApi.doSomeAsyncThing
)时挂接/绑定(bind)它们
最后,使用 $.when 的替代方法是手动跟踪事物,可能使用计数器。例如:
var counter = 2; // set your number of ops here
var checkIfFinished = function(){
if(--counter === 0) {
triggerAllEventsCompleteFunc(); // replace this with your desired action
}
}
// call checkIfFinished in all your callbacks
关于javascript - 混合回调函数和 jQuery 延迟队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15750343/