jQuery - .always()回调解雇太快了

时间:2015-06-11 20:17:04

标签: javascript jquery jquery-deferred

我正在开发一个客户端JS应用程序,该应用程序应该读取CSV文件,每行进行一些API调用,然后将结果写回CSV。我坚持的部分是如何编排请求并在完成所有功能时启动一个功能。这就是我到目前为止所做的:

var requests = [];

// loop through rows
addresses.forEach(function (address, i) {
    // make request
    var addressRequest = $.ajax({
            dataType: 'json',
            url: 'http://api.com/addresses/' + address,
            success: function (data, textStatus, jqXhr) { APP.didGetAddressJson(data, i, jqXhr) },
            error: function (jqXhr, textStatus, errorThrown) { APP.didFailToGetAddressJson(errorThrown, i) },
        });
    requests.push(addressRequest);

    // make some more requests (handled by other success functions)
});

// leggo
$.when.apply($, requests).done(APP.didFinishGeocoding);

问题是,如果其中一行抛出404,则不会调用done函数。我把它切换到always现在它被调用了,但最后却没有 - 如果我将每个回调的执行记录到控制台,它通常位于中间位置。但是,如果我编辑CSV以便没有错误,则会按预期在最后调用它。我在这里做的事情是允许always早点开火吗?

更新:可能就是控制台正在记录out of order吗?

2 个答案:

答案 0 :(得分:2)

您需要防止错误发送$.when.apply($, requests)返回错误路径的错误。

这可以通过以下方式实现:

  • .then()链接到您的$.ajax()来电,而不是指定"成功"和"错误"处理程序为$.ajax()选项。
  • 通过转换为成功来处理错误(因为这是jQuery,您必须从错误处理程序返回已解析的promise)。

此方法还允许您控制最终传递到APP.didFinishGeocoding()

的数据

通过一些假设,代码的一般形状应如下所示:

function foo () {//assume there's an outer function wrapper 
    var errorMarker = '**error**';

    var requests = addresses.map(function (address, i) {
        return $.ajax({
            dataType: 'json',
            url: 'http://api.com/addresses/' + address
        }).then(function (data, textStatus, jqXhr) { //success handler
            return APP.didGetAddressJson(data, i, jqXhr); //whatever APP.didGetAddressJson() returns will appear as a result at the next stage.
        }, function (jqXhr, textStatus, errorThrown) { // error handler
            APP.didFailToGetAddressJson(errorThrown, i);
            return $.when(errorMarker);//errorMarker will appear as a result at the next stage - but can be filtered out.
        });
        // make some more requests (handled by other success functions)
    });

    return $.when.apply($, requests).then(function() {
        //first, convert arguments to an array and filter out the errors
        var results = Array.prototype.slice.call(arguments).filter(function(r) {
            return r !== errorMarker;
        });

        //then call APP.didFinishGeocoding() with the filtered results as individual arguments.
        return APP.didFinishGeocoding.apply(APP, results);

        //alternatively, call APP.didFinishGeocoding() with the filtered results as an array.
        //return APP.didFinishGeocoding(results);
    });
}

根据需要调整。

答案 1 :(得分:1)

尝试通过whenAll函数传递已解析,被拒绝的jQuery promise对象,在.then()完成时过滤已解析,被拒绝的承诺对象whenAll。另请参阅Jquery Ajax prevent fail in a deferred sequential loop

(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));

e.g

var request = function (url) {
    return $.ajax({
                   url: "http://api.com/addresses/" + url, 
                   dataType: "json"
           })
    }
, addresses = [
    ["/echo/json/"], // `success`
    ["/echo/jsons/"], // `error`
    ["/echo/json/"], // `success`
    ["/echo/jsons/"], // `error`
    ["/echo/json/"] // `success`
];

$.when.all(
  $.map(addresses, function (address) {
    return request(address)
  })
)
.then(function (data) {
    console.log(data);
    // filter , process responses
    $.each(data, function(key, value) {
        if (key === "success") {
           value.forEach(function(success, i) {
              console.log(success, i);
              APP.didGetAddressJson(success.data, i, success.jqxhr);
            })
        } else {            
           value.forEach(function(error, i) {
              console.log(error, i);
              APP.didFailToGetAddressJson(error.jqxhr, i)
          })
        }
    })
}, function (e) {
    console.log("error", e)
});

jsfiddle http://jsfiddle.net/guest271314/ev4urod1/