使用jQuery Deferred查找第一个可用的数据源 [英] Find first available data source with jQuery Deferred

查看:92
本文介绍了使用jQuery Deferred查找第一个可用的数据源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在接受采访时被问到这个问题,但它提出了一个很好的用例。假设您有一堆数据源。你想找到第一个可用的并处理它而忽略其余的。

So I was asked this at an interview, but it brought up a good use case. Assume that you have a bunch of data sources. You want to find the first available one and process it and ignore the rest.

所以类似于:

var datasources = new Array("somedatabase1/pizza","somedatabase2/beer","somedatabase3/llama");
var dfds = new Array();
$.each(datasources,function(source){
    dfds.push($.getJSON(source));
});

$.when(dfds).done(function(){alert("they are all done");});

忽略我真的不认为何时接受一个数组(也许它确实如此)。这当然会让它等到它们全部完成。我正在寻找一些代码让它等到一个,其中任何一个完成,然后不用担心其他代码。

Ignore that I really don't think when accepts an array (maybe it does). This of course would make it wait till they are all completed. I am looking for some code that would make it wait until one, any of them is done, and then not worry about the others.

我被告知它只会递归地工作。

I was informed that it would only work recursively.

推荐答案

这不使用递归但符合从多个数据源获取的要求而只关心第一个返回成功的回复。

This doesn't use recursion but fits the requirement to fetch from multiple datasources and only care about the first that returns a successful response.

http://jsfiddle.net/ mNJ6D /

function raceToIt(urls) {
    var deferred = $.Deferred(),
        promises;

    function anyComplete(data) {
        if (!deferred.isResolved()) {
            deferred.resolveWith(this, [data]);
            promises.forEach(function(promise) {
                promise.abort();
            });
        }
    }
    promises = urls.map(function(url) {
        return $.getJSON(url).then(anyComplete);
    });
    return deferred.promise();
}
raceToIt(["/echo/json/", "/echo/json/", "/echo/json/"]).then(function(data) {
    console.log(data);
});​

这篇关于使用jQuery Deferred查找第一个可用的数据源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆