Having issues with resolving or rejecting promises when using $http get requests

I am facing a challenge in rejecting a deferred object within a $http.get call as it is not getting properly rejected. The error callback does not get triggered, and I'm struggling to understand why this is happening. Here is an outline of what my code looks like:

var promise = this.SomeAsyncCall(this.$.SomeID)
                .then(
                    function () 
                    {
                        service.SendAsyncDownloadReqeuest(someOtherID);
                    },
                this.ErrorHandler.HandleError)
                  .then(this._DownloadInitiated, this.ErrorHandler.HandleError);
              promise["finally"](this._DownloadRequestFinished);

Below is the code for service.SendAsyncDownloadRequest:

var SendAsyncDownloadReqeuest = function (ID)
{
    var url = "someUrl?ID=" + customerID;
    var navigator = self.$window.navigator;
    var window = self.$window;
    var deferred = self.$q.defer();
    self.$http.get(url, { responseType: 'arraybuffer' })
    .success( function(data, status, headers) {
        var success = false;
        //Initiate download via blob. Set success

        success ? deferred.resolve() : deferred.reject();
    })
    .error(function (data, status)
    {
        var error = 
        { 
           //Some error properties 
        }
        deferred.reject(error);
    });

    return deferred.promise;
};

Even though when returning a 500 status code from the server, the code reaches the .error block of the http get call and executes the reject line. However, the ErrorHandler's HandleError method is not being called. It's worth noting that the HandleError method works fine with error callbacks for promises rejected in scenarios other than $http.get calls.

Answer №1

Ensure that the promise returned from

service.SendAsyncDownloadReqeuest(someOtherID);
is passed back to the HandleError function in your code. Here is how you can update it:

var promise = this.SomeAsyncCall(this.$.SomeID)
                .then(
                    function () 
                    {
                        return service.SendAsyncDownloadReqeuest(someOtherID);
                    },
                this.ErrorHandler.HandleError)
                  .then(this._DownloadInitiated, this.ErrorHandler.HandleError);
              promise["finally"](this._DownloadRequestFinished);

To enhance clarity, consider revising it like this:

var promise = this.SomeAsyncCall(this.$.SomeID)
                  .then(function () {
                         service.SendAsyncDownloadReqeuest(someOtherID).then(
                           this._DownloadInitiated,
                           this.ErrorHandler.HandleError);
                  },
                  this.ErrorHandler.HandleError);
promise["finally"](this._DownloadRequestFinished);

Answer №2

Avoid using the outdated success method in both scenarios. Both methods have been marked as deprecated.

The $http legacy promise methods success and error are no longer supported. It is recommended to use the standard then method instead. If you have set $httpProvider.useLegacyPromiseExtensions to false, attempting to use these methods will result in a $http/legacy error being thrown.

Here is a more concise method example:

$http.post('/someUrl', data, config).then(successCallback, errorCallback);

And here is a longer example demonstrating a GET request:

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // This callback will be invoked asynchronously
    // once the response is available
  }, function errorCallback(response) {
    // This callback will be triggered asynchronously in case of an error
    // or if the server responds with an error status
  });

Official Documentation

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to change data into an array using Java script?

In this code snippet, I am utilizing a loop to send data to an ajax function in JSON format: foreach($careers->getItems() as $item){ if($item->getDepartment()==$departmentID && $item->getLocation()==$location ...

Having trouble accessing the Ajax "data" parameter in Twisted

An ajax request is made using the "POST" method with these parameters: function sendDataToServer(portNumber){ console.log(portNumber) $.ajax({url: "action", dataType : 'html', type: "POST", data: portN ...

Creating an Angular table using reactive forms: a step-by-step guide

After reviewing the HTML snippet provided below, it is evident that there is a table with looping through mat cell using *matCellDef="let model". Inside each cell, there are input fields which are reactive forms. Each row or cell needs to have it ...

Strategies for simplifying this extensive if/else block

My current if/else statement in React Native is functional but seems verbose. I am curious to know how other developers would optimize and shorten it. I feel like my code represents a beginner's approach, and I welcome suggestions on how to improve i ...

Monochrome Effect Triggered by Cursor Hover

I'm attempting to use Javascript with HTML5 canvas to convert an image to greyscale, but I seem to be missing something in my code. Can anyone spot the error? I feel like I'm very close! function grayscaleConversion(str) { // Access the Canv ...

Using JavaScript's DOM manipulation to switch out one HTML tag for another

As a newbie to javascript and DOM, I'm facing an issue with manipulating DOM elements using javascript in the given HTML code. <html> <head> <title>Testing</title> </head> <body> <marquee direction=up heig ...

Transferring information between a modal and a controller

Looking to make data accessible in a controller? I've put together a simplistic Plunk to demonstrate displaying data on the $scope within a modal. The goal is to be able to update the data, with changes reflected in the $scope only upon clicking "ok". ...

Is there a way to trigger an action every 5 minutes in ReactJS?

I am attempting to trigger an action every 5 minutes after a user logs in. The action should only be dispatched once the user is logged in and then continue at 5-minute intervals. I initially tried using the setInterval method, but encountered an issue whe ...

Is there a way to only allow the active video to play while disabling the others in this Vue 3 and Bootstrap 5 carousel?

I'm currently developing a Single Page Application (SPA) using Vue 3, TypeScript, and The Movie Database (TMDB). Additionally, I'm incorporating Bootstrap 5 for the UI. To showcase movie trailers on the movie details page, I've created the ...

Exploring object-level "this" behavior in jQuery

If I were to implement the following code snippet: const CustomObject = function() { this.showAlert = function() { alert("Hello World!"); } } CustomObject.prototype.bindToElement = function(element) { const self = this; $(element).bind(' ...

Tips on separating a function into two separate files in Node.js

Hey there! I am just starting to explore Node.js so bear with me if I make any mistakes. So, I have this file: exports.Client = function() { this.example = function(name, callback) { console.log(name); }; ...

Meteor powering the user interface, while Express handles the server-side operations on the backend with NodeJS

When designing a website that requires real-time reactivity like Meteor on the frontend, but also needs a job processing backend (such as Kue), it is clear that the frontend app will benefit from Meteor's capabilities. However, the backend processing ...

The functionality of `onclick="location.href='link.html'" seems to be malfunctioning

Trying to find a way to include onclick="location.href='link.html'" in my code. I want to make it so that when a user clicks on an image, they are directed to a specific URL. I'm not exactly sure how to implement this in the code below. Her ...

Ways to synchronize countdown timer on different tabs using the same link

Is there a method available to synchronize a React countdown timer across two separate tabs, for example: 1:46          ||   1:52 first tab     ||   second tab Appreciate any help! ...

Avoid using single quotes in Postgres queries for a more secure Node.js application

Snippet from my node js code: var qry = 'INSERT INTO "sma"."RMD"("UserId","Favourite") VALUES (' + req.body.user + ',' + JSON.stringify(req.body.favourite) + ')' My problem is inserting single quotes before JSON.stringify(r ...

Store the uploaded file with angular-file-upload to preserve it for later use

I've been working on a page that utilizes the Angular File Upload component from https://github.com/nervgh/angular-file-upload/wiki/Module-API. However, I'm facing difficulties in retrieving and saving the uploaded file information to disk. I&ap ...

What is the best way to make JavaScript display the strings in an array as bullet points on different lines?

We were assigned a task in our computer science class to analyze and extend a piece of code provided to us. Here is the given code snippet: <!DOCTYPE html> <html> <head> <title>Example Website</title> </head> <body& ...

Error message encountered: Missing property status in TypeScript code

An error occurs in the refetchInterval when accessing data.status, with a message saying "property status does not exist" chatwrapper.tsx const ChatWrapper = ({ fileId }: ChatWrapperProps) => { const { data, isLoading } = trpc.getFileUploadStatus.use ...

Exploring the World of PHP, MySQL, and AJAX

Recently, I came across an issue where I needed to extract values from a MySQL database using JavaScript. What I intended to achieve was to dynamically add a div element when a PHP page is loaded for editing information. The plan was to populate this div w ...

What is the method to retrieve the index or row number using the map function in Google Sheets?

Currently, I am attempting to retrieve the row number where the row meets certain criteria. However, I seem to be encountering an issue: Instead of getting the desired result, I am obtaining an array like this: [,,2] Although I have attempted using filter ...