使用 promises 数组和 $.when 忽略 AJAX 错误 [英] Ignoring AJAX errors with promises array and $.when

查看:13
本文介绍了使用 promises 数组和 $.when 忽略 AJAX 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码从一系列 YouTube 视频 ID 中获取 JSON.当所有视频都存在并且查询成功时,它效果很好.它发送几个 getJSON 请求,当所有请求都完成后……$.when.done() 会触发,我可以处理结果数据.

I have the following code that gets the JSON from an array of YouTube video ids. It works great when all the videos exists and the query is successful. It sends several getJSON request, and when all of them are done... the $.when.done() fires and I can process the resulting data.

var
  results  = {},
  promises = [];

$(document).ready(function() {

  var
    vids = [
    'ozj2-bnTL3s',
    'EAZ4Tlt8MQ4',
    'Xn9o7cxqVoA'
    // ,'this-videoid-doesnot-exists'
  ],
  url = 'http://gdata.youtube.com/feeds/api/videos/{{vid}}?v=2&alt=json';

  $.each(vids, function(idx, vid){
    var
      u = url.replace('{{vid}}', vids[idx]),
      p = null;

    p = $.getJSON( u ).done(function(data) {
      results[vid] = data.entry;
    });

    promises.push(p);
  });

  $.when.apply($, promises).done(function(){
    console.log(results);
  });

});

但是...在最终的应用程序中,我无法控制所有视频是否仍然存在于 YouTube 中,我意识到有时列表中的一个(或多个)视频可能已被删除...或我从数据库获得的 ID 不正确.

But... In the final app I don't control if all the videos still exists in YouTube, I've realized that sometimes one (or several) of the videos in the list may have been deleted... or the id that I get from the DB is incorrect.

有什么方法可以安全地将仅那些成功的白化触发 $.when.fail() 的视频添加到结果变量中? 并等待所有查询都完成...

Is there any way that I could safely add to the results variable only the videos that where successful whiteout trigger the $.when.fail()? and waiting that all the queries had finished...

我的意思是,我的最终目标是从存在的视频中获取数据(那些已成功检索其数据的视频),并且以某种方式忽略那些不存在或不可用的视频......而我没有不知道现在该怎么做.

I mean, my final goal is to get the data from the videos that exist (those that its data was successfully retrieved), and, somehow to ignore those that don't exist or where unavailable... and I don't figure right now how to do it.

任何想法/方法都会得到认可.TIA!
你可以在这个JSFiddle

Any idea / approach will be appretiated. TIA!
You can find the code in this JSFiddle

推荐答案

遗憾的是,jQuery 没有提供此功能.

Unfortunately, jQuery doesn't come with this functionality.

很高兴,您可以很容易地自己实现它.

Gladly, you can implement it yourself pretty easily.

var url = 'http://gdata.youtube.com/feeds/api/videos/{{vid}}?v=2&alt=json';
function getVideo(vid){
    var u = url.replace('{{vid}}', vid);
    return $.getJSON( u ).then(function(res){
         return {video:vid,result:res.entry};
    });
}
var promises = ['ozj2-bnTL3s','EAZ4Tlt8MQ4',"doesn'texist"].map(getVideo);

some(promises).then(function(results){
    for(var i = 0; i < results.length; i++) {
        console.log(results[i]); // log
    }
});



// get a hook on when all of the promises resolve, some fulfill
// this is reusable, you can use this whenever you need to hook on some promises
// fulfilling but all resolving.
function some(promises){
    var d = $.Deferred(), results = [];
    var remaining = promises.length;
    for(var i = 0; i < promises.length; i++){
        promises[i].then(function(res){
            results.push(res); // on success, add to results
        }).always(function(res){
            remaining--; // always mark as finished
            if(!remaining) d.resolve(results);
        })
    }
    return d.promise(); // return a promise on the remaining values
}

这是结果的 工作 JSFiddle.

这篇关于使用 promises 数组和 $.when 忽略 AJAX 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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