如何订购几个异步JQuery查询的结果?

时间:2014-06-08 22:33:47

标签: javascript jquery

我从多个网络服务中提取信息以显示在网页上。我希望能够订购结果,但保持动态。但是,我构建代码的方式意味着元素按请求完成的顺序插入到DOM中,这是非确定性的。我如何保证特定订单,但避免插入“dud'元素如果其中一个结果错误而不是返回有效信息?

// Get my apps from iTunes
var iTunesLinks = ["525393529", "645218452", "737479996"];
var iTunesSquareSize = 128;

$.each(iTunesLinks, function(index, value) {

    var iTunesLink = "https://itunes.apple.com/lookup?id=" + value + "&callback=?";

    $.getJSON(iTunesLink, function(data) {

       var items = [];
       items.push("<section id=\"myApps\"><table>");

       var results = data.results;

       $.each ( results, function( key, val ) {

            var appName = val.trackName;
            var iconURL = val.artworkUrl100;
            var appURL = val.trackViewUrl;
            items.push( "<td align=center width=" + iTunesSquareSize + " style=\"vertical-align:top\">" + divStart + "<a href=" + appURL + " target=_blank><img src=\"" + iconURL + "\" width=" + iTunesSquareSize + " height=" + iTunesSquareSize + "></a></div><a href=" + appURL + " target=_blank>" + appName + "</a></td>" );     
       });

       items.push("</table></section>");

       $( "<td/>", {
         "class": "applist",
         html: items.join( "" )
       }).appendTo( document.getElementById("myApps") );
    });
});

1 个答案:

答案 0 :(得分:4)

您可以将所有承诺收集到一个数组中,然后将其传递给$.when(),然后在解决之后,您将获得所有async ajax调用中的所有数据,如下所示:

// Get my apps from iTunes
var iTunesLinks = ["525393529", "645218452", "737479996"];
var iTunesSquareSize = 128;
var promises = [];

$.each(iTunesLinks, function(index, value) {

    var iTunesLink = "https://itunes.apple.com/lookup?id=" + value + "&callback=?";
    promises.push($.getJSON(iTunesLink));

});

$.when.apply($, promises).done(function(/* arg1Array, arg2Array, arg3Array, ... */) {
    // now process all the results in order
    var items, results;
    for (var i = 0; i < arguments.length; i++) {
        // arguments[i] is an array of [data, statusText, jqXHR]
        results = arguments[i][0].results;
        items = [];
        items.push("<section id=\"myApps\"><table>");

        $.each ( results, function( key, val ) {

            var appName = val.trackName;
            var iconURL = val.artworkUrl100;
            var appURL = val.trackViewUrl;
            items.push( "<td align=center width=" + iTunesSquareSize + " style=\"vertical-align:top\">" + divStart + "<a href=" + appURL + " target=_blank><img src=\"" + iconURL + "\" width=" + iTunesSquareSize + " height=" + iTunesSquareSize + "></a></div><a href=" + appURL + " target=_blank>" + appName + "</a></td>" );     
        });

        items.push("</table></section>");

        $( "<td/>", {
         "class": "applist",
         html: items.join( "" )
        }).appendTo( document.getElementById("myApps") );
    }
});