angularjs $q then() > catch() > then(), 取消最后一个then()的执行

angularjs $q then() > catch() > then(), cancel execution of last then()

我有以下代码(为简洁起见进行了简化):

var makeRequest = function (method, url, query, data) {
    var request = {
        method: method,
        url: url,
        params: query || {},
        paramSerializer: '$httpParamSerializerJQLike',
        data: data || {},
        timeout: 10000
    };

    if (method === 'POST' || method === 'PUT') {
        request.headers = { 'Content-Type': 'application/json; charset=UTF-8' };
    }

    return $http(request)
        .then(function (response) {
            response = normalizeResponse(response.data); // ensures {result, data, msg}

            if (!response.result) {
                throw {data: response};
            }

            return response;
        })
        .catch(function (response) {
            Notify('error', response.data.msg);
        });
};

调用方式如下:

makeRequest('GET', '/user').then(function (response) {
    console.log('user=', response.data);
});

这对于成功的请求来说工作正常,但是一旦我发出失败的请求,我就会得到一个 TypeError: Cannot read property 'data' of undefined,因为 catch() 没有(也不应该)return 任何东西, 但第二个 then() promise 仍然被执行。

我希望 catch() 是最后执行的,如果请求本身失败,任何进一步的 then() 调用都不会执行。 catch 块在整个系统中是通用的,因此将它复制粘贴到各处是没有意义的,它不是 DRY。有可能还是我必须为此做一些肮脏的黑客攻击?

注意:如果请求成功,我仍然希望 promise 链接可用。

catch 块 "rescues" 承诺并允许 .then 稍后的调用正常进行。如果你想避免这种行为,只需在 catch 块中重新抛出错误即可。

.catch(function (response) {
  Notify('error', response.data.msg);
  throw response.data.msg;
});