使用Q.js链接多个ajax调用并集中处理错误

时间:2016-06-23 15:08:43

标签: javascript q deferred

如果其中任何一个调用失败,我想链接多个ajax调用并处理错误(登录到数据库)。

我的ajax调用代码是这样的:

var ajaxCalls = {
        /// <summary>
        /// Register ajaxCalls here
        /// </summary>
        //Get all bridge codes
        getBridgeCode: function () {
            var deferred = q.defer();
                jQuery.ajax({
                    url: window.routeDictionary.codeTable.GetBridgeCode,
                    type: 'GET',
                    }).then(function (data, textStatus, jqXHR) {
                    delete jqXHR.then; // treat xhr as a non-promise
                    deferred.resolve(data);
                }, function (jqXHR, textStatus, errorThrown) {
                    delete jqXHR.then; // treat xhr as a non-promise
                    helperPlugins.removeWait();
                    deferred.reject(new Error(jqXHR));
                });
                return deferred.promise;
        },
        getRouteCode: function () {
            var deferred = q.defer();
            jQuery.ajax({
                url: window.routeDictionary.codeTable.GetRouteCode,
                type: 'GET',
            }).then(function (data, textStatus, jqXHR) {
                delete jqXHR.then; // treat xhr as a non-promise
                deferred.resolve(data);
            }, function (jqXHR, textStatus, errorThrown) {
                delete jqXHR.then; // treat xhr as a non-promise
                helperPlugins.removeWait();
                deferred.reject(new Error(jqXHR));
            });
            return deferred.promise;
        },
        getOtherCode: function () {
            var deferred = q.defer();
            jQuery.ajax({
                url: window.routeDictionary.codeTable.GetOtherCode,
                type: 'GET',
            }).then(function (data, textStatus, jqXHR) {
                delete jqXHR.then; // treat xhr as a non-promise
                deferred.resolve(data);
            }, function (jqXHR, textStatus, errorThrown) {
                delete jqXHR.then; // treat xhr as a non-promise
                helperPlugins.removeWait();
                deferred.reject(new Error(jqXHR));
            });
            return deferred.promise;
        },
    }

我调用ajax调用的方法是这样的:

 helperPlugins.showWait('Getting Bridge Codes');
    ajaxCalls.getBridgeCode().then(function(value) {
        helperPlugins.showWait('Getting Route Codes');
        ajaxCalls.getRouteCode().then(function (value) {
            helperPlugins.showWait('Getting Other Codes');
            ajaxCalls.getOtherCode().then(function (value) {
            helperPlugins.removeWait();
         }).fail(function(error) {
            return "Not Found";
        }).then(console.log);
    });
});

函数getRouteCode和getOtherCode将失败,因为控制器不存在。我能够到达deferred.reject(new Error(jqXHR)); 在getRouteCode上,但之后没有。

我做错了什么?

0 个答案:

没有答案