Angular Promise Conditional

My Angular v1.x directive calls a function when a button is clicked and depending on the input I set some variables:

$scope.offerRespond = function() {

        if (offer.i.offerResponse == 1) {  
             // set some variables
        }

        else if (offer.i.offerResponse == 0) { 

             $http({method: 'GET', url: frontbaseurl+'/offer_types/' + id + '.json'})
             .then(function successCallback(response) { 
                  $scope.reason = response.data.data.name;
             }, function errorCallback() {
                  $scope.reason = "Unknown";
             }

        );

        $http.post(frontbaseurl+'/purchases.json', JSON.stringify(dataObj))
        .then(function(response){ 

             // continue....

        }
}

As can be seen, I make a GET request if the offerResponse == 0. This seems risky because the code continues to execute without before a response from the request is received. I know the approach is to use a 'promise' but how does that apply in this case if the GET request may not be made?

The problem as I see it is if I add a promise and the offerResponse == 1 the promise can't be fulfilled since the GET request would not have been made.

Any suggestions please?

1 answer

  • answered 2018-09-25 02:02 Ben

    I've had to do something similar in our angular 1.x app, using Typescript, like this:

    public myFunc = async (id): Promise<void> => {
        return new Promise<void>(async (resolve, reject) => {
            if (this.offer.i.offerResponse === 1) {  
                // set some variables
                resolve();
            }
            else if (this.offer.i.offerResponse === 0) { 
    
                try {
                    const response = await services.getOfferTypes(id);
                    this.reason = response.data.data.name;
                    resolve();
                } catch (errorResponse) {
                    this.reason = "Unknown";
                    reject();
                }
            }
        });
    }
    

    Notice I "encapsulated" your http request in a service function. I like separating api calls into their own service, to keep things clean and easy to read. This code is untested, but if I remember correctly it should work something like this.