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

后端 未结 2 1364
孤独总比滥情好
孤独总比滥情好 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 19:04

    To prevent a rejection handler from converting a rejected promise to a fulfilled promise it is important use a throw statement in the rejection handler:

    var getSubmit = function (request) {
        return SparkRequestService
            .submitRequest(request)
            .then(
                function (resData) {
                    console.log("resData", resData);
                    enrollmentService.resetEnrollment();
                    return resData;
                }, 
                function (errorResponse) {
                    console.log('error');
                    //IMPORTANT
                    //throw to chain rejection
                    throw errorResponse;
                }
            );
    }
    

    When a function omits a return or throw statement, the function returns a value of undefined. This will convert a rejected promise to a fulfilled promise that resolves with a value of undefined.


    Problem is that ... it is a business error wrapped up in a return object

    To convert a fulfilled promise to a rejected promise, use a throw statement.

    this.submitEnrollment = function (enrollment) {
        var promise = getSubmit(requestData);
        var newPromise = promise.then(function(response) {
             if (response.data.hasErrors) {
                 console.log(response.data.errorList);
                 response.data.errorList.push("submitEnrollent: Rejected"); 
                 //THROW to create rejection
                 throw response;
             } else {
                 //RETURN response to chain success
                 return response;
             }
        });
        return newPromise;
    }
    

    When a promise is converted to a rejection, all subsequent success handlers in the chain will be skipped. The chain will be followed until a rejection handler is found.

提交回复
热议问题