Promise Chaining is not working as expected

I am trying use the promise chaining for the $http.get calls I am making from my angular application

$http.get(url, config)
    .then(newViewRequest)
    .then(function (response) { // success async
        $scope.viewRequest1.data = response.data;
    }

And in my newViewRequest I making a new call to other end point and I need to only send the response back if the call with in the newViewRequest is successful. Below is what I am trying

var newViewRequest = function (response) {
    var url1 = $rootScope.BaseURL;
    var config = {
        headers: {
            'Authorization': `Basic ${$scope.key}`,
            'Prefer': 'odata.maxpagesize=2000'
        }
    }; 

    var newresponse = $http.get(url1, config);
    if (newresponse.status = 200)
        return newresponse;
    else return response;
};

But it always send the request response with out validating the status or anything. How can I approach this.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

The $http.get in newViewRequest returns a Promise. You need to wait for it to resolve to get get the status. And you have to return the Promise from newViewRequest to do proper chaining.

return $http.get(url1, config)
.then(newresponse => {
  if (newresponse.status = 200)
    return newresponse;
  else return response;
})
.catch(err => {
  return response;
})

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply