jQuery的阿贾克斯prevent失败的递延顺序循环 [英] Jquery Ajax prevent fail in a deferred sequential loop

查看:96
本文介绍了jQuery的阿贾克斯prevent失败的递延顺序循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我串联起来顺序阿贾克斯,加载URL的数组中的顺序。原来我用。那么()而不是。总是(),并且无论哪种方式,它工作得很好 - 只要所有网址存在。然而,因为有文件丢失的可能性,我想弥补这一点,然后最后,告知其档案失踪的用户,以使其更容易纠正。

So, I'm chaining together sequential ajax, to load an array of urls in order. Originally I used .then() instead of .always(), and either way it works fine - provided that all urls existed. However, since there's a possibility of missing files, I wanted to compensate for that, and then finally, inform the user of which files were missing, in order to make it easier to rectify.

然而,问题是,在一个丢失的文件/ 404,code执行,像它应该,但后来退出循环,preventing任何进一步的Ajax调用。所以我想,我需要一些方法或者办理失败()并迫使成功不分,或覆盖在404的默认行为的一些其他的方式,所以它继续前进通过循环。

However, the problem is, on a missing file/404, the code executes, like it should, but then exits the loop, preventing any further ajax calls. So I figure, I need some way of either handling the fail() and forcing a success regardless, or some other way of overriding the default behavior on a 404, so it continues progressing through the loop.

不幸的是,最近谷歌的结果,是如何做相反的(强制的成功失败)。

Unfortunately, the closest Google results, were how to do the opposite (force a failure on success).

var missing=[];
uLoadList.reduce(function(prev, cur, index) {
    return prev.then(function(data) {
        return $.ajax("/wiki/"+cur).always(function(data) {
            var temp = $('#mw-content-text',data);
            temp = $('pre',temp);
            if(temp.length > 0)
            {
                //handle success
            }else{
                //handle failure
                missing.push(cur);
            }
        });
    });
}, $().promise()).done(function() {
    if(missing.length > 0)
    {
        //notify of missing objects
    }
    //continue on.
});

最后一个音符,以缓解困惑:该URL和脚本本身,是一个的MediaWiki站点 - 所以即使404返回,总是会有页面内容,并且将包含与该ID的元素 MW-内容文本。

One final note, to alleviate confusion: the URLs, and the script itself, are on a MediaWiki site - so even if a 404 is returned, there will always be page content, and will contain the element with the id of "mw-content-text".

推荐答案

尝试

(function ($) {
    $.when.all = whenAll;
    function whenAll(arr) {
        "use strict";
        var deferred = new $.Deferred(),
            args = !! arr 
                   ? $.isArray(arr) 
                     ? arr 
                     : Array.prototype.slice.call(arguments)
                       .map(function (p) {
                         return p.hasOwnProperty("promise") 
                         ? p 
                         : new $.Deferred()
                           .resolve(p, null, deferred.promise())
                       }) 
                   : [deferred.resolve(deferred.promise())],
            promises = {
                "success": [],
                  "error": []
            }, doneCallback = function (res) {
                promises[this.state() === "resolved" 
                         || res.textStatus === "success" 
                         ? "success" 
                         : "error"].push(res);
                return (promises.success.length 
                       + promises.error.length) === args.length 
                       ? deferred.resolve(promises) 
                       : res
            }, failCallback = function (res) {
                // do `error` notification , processing stuff
                // console.log(res.textStatus);
                promises[this.state() === "rejected" 
                        || res.textStatus === "error" 
                        ? "error" 
                        : "success"].push(res);
                return (promises.success.length 
                       + promises.error.length) === args.length 
                       ? deferred.resolve(promises) 
                       : res
            };
        $.map(args, function (promise, index) {
            return $.when(promise).always(function (data, textStatus, jqxhr) {
                return (textStatus === "success") 
                    ? doneCallback.call(jqxhr, {
                        data: data,
                        textStatus: textStatus 
                                    ? textStatus 
                                    : jqxhr.state() === "resolved" 
                                      ? "success" 
                                      : "error",
                        jqxhr: jqxhr
                      }) 
                    : failCallback.call(data, {
                        data: data,
                        textStatus: textStatus,
                        jqxhr: jqxhr
                      })
            })
        });
        return deferred.promise()
    };
}(jQuery));
// returns `Object {
//                   success: Array[/* success responses*/], 
//                   error: Array[/* error responses */]
//          }`


// e.g.,
var request = function (url, data) {
    return $.post(url, {
        json: JSON.stringify(data)
    })
}, settings = [
    ["/echo/json/", "success1"], // `success`
    ["/echo/jsons/", "error1"], // `error`
    ["/echo/json/", "success2"], // `success`
    ["/echo/jsons/", "error2"], // `error`
    ["/echo/json/", "success3"] // `success`
];

$.when.all(
  $.map(settings, function (p) {
    return request.apply($, p)
  })
)
.then(function (data) {
    console.log(data);
    // filter , process responses
    $.each(data, function(key, value) {
        if (key === "success") {
          results.append(
              "\r\n" + key + ":\r\n" + JSON.stringify(value, null, 4)
          )
        } else {            
          results.append(
              "\r\n" + key + ":\r\n" 
              + JSON.stringify(
                  value.map(function(v, k) {
                    v.data.responseText = $(v.data.responseText)
                      .filter("title, #summary, #explanation")
                      .text().replace(/\s+/g, " ");
                    return v
                  })
                , null, 4)
          )
        }
    })
}, function (e) {
    console.log("error", e)
});

http://jsfiddle.net/guest271314/620p8q8h/

这篇关于jQuery的阿贾克斯prevent失败的递延顺序循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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