Angular Promises and Chaining: How to break a chain if it has business data errors

后端 未结 2 1343
孤独总比滥情好
孤独总比滥情好 2021-01-16 18:31

I thought that I had this all figured out on previous projects through the years.. Apparently not.

Goal : Take Service that calls other Services and if there is any

2条回答
  •  醉梦人生
    2021-01-16 18:45

    it seems that the promise returned by SparkRequestService.submitRequest(request) is not rejected when you get the error inside resData. For this reason the successCallback of then is invoked and not the second one, the errorCallback.

    For this reason, inside the successCallback you need to inspect the data of resData to check errors and behave accordingly, for example:

    var getSubmit = function (request) {
        return SparkRequestService
            .submitRequest(request)
            .then(function (resData) {
                    console.log("resData", resData);
                    if(resData === null) { // Check for errors
                        // There is an error, manage it inside this block of code
                        // ...
                        // You can also create a rejected promise with $q.reject() and passing resData containing the errors
                        return $q.reject(resData);
                    } else {
                        // Call resetEnrollment() in the ELSE branch so, it is executed only if resData does not contain errors
                        enrollmentService.resetEnrollment();
                        return resData;
                    }
                }, 
                function (resData) {
                    console.log('error');
                }
            );
    };
    

提交回复
热议问题