混合回调函数队列和jQuery延迟

时间:2013-04-01 19:30:32

标签: javascript jquery jquery-ui jquery-ui-autocomplete jquery-deferred

我正在尝试创建一个要调用的函数队列来返回自动完成结果。其中一些是我自己从$ .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调用完成,它就会返回。很明显,我没有正确连接所提供的功能,但我不知道该怎么做。

1 个答案:

答案 0 :(得分:2)

如果您已经开始使用$ .when,那么您将需要创建一个延迟数组,因此您可以像这样调用提供的函数:

functionQueue.push( (function(){
        var df = new $.Deferred();
        providedFunction(searchTerm, function(data) {
            allResults.push.apply(allResults, data);
            df.resolve();
        })
        return df;
    })()
);

当然,如果您觉得自己真的很喜欢,可以使用这个方便的实用程序将基于回调的API转换为基于承诺/延期的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),请暂停/绑定API函数

最后,使用$ .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