Send back an error using a promise

I am fairly new to AngularJS and Javascript. I am currently working on an application where I intend to use a single function for all Ajax operations (a factory in AngularJS). This function will serve as the gateway for all Ajax requests. While returning a promise as successful works fine, returning an error promise does not seem to work.

Below is a sample code snippet. I expect the error function to return a promise if the initial promise fails, but it always triggers the success function instead.

var myApp = angular.module('myApp', []);

myApp.controller('FirstController, function($scope, util){
        util.doAjax().then(function(response){
                // This function gets called in both success and error scenarios
            }, function(err){
                // This block is never executed, which raises questions                
            });
});

myApp.factory('util, function($http){
    return $http({
       method: 'GET',
       url: 'http://www.example.com'
    }).then(function(response){
        // This returns a success promise
        return response;
    }, function(err){
        // Expecting this block to return an error promise
        return err;
    });
});

Answer №1

Your current approach involves directly returning data from the error function, leading to chaining of the promise and calling the underlying .then method.

When returning an error, it is important to reject a promise by creating a new custom promise using $q.

return $q.reject(err)

Another essential point to consider is creating a method in a service with a specific name.

myApp.factory('util', function($http, $q){
 //Exposed method
 return {
   doAjax : function() {
       return $http({
          method: 'GET',
          url: 'http://www.example.com'
       }).then(function(response){
           // This will return success promise
           return response.data; // returned data
       }, function(err){
           // return error promise with err object
           return $q.reject(err);
       });
     }
  }
});

Answer №2

In order to avoid returning a promise, you should ensure that you return the $http promise instead. Here is an example of how to do so:

myApp.factory('util', function($http){

    return {
        ajax: function () {
            var httpPromise = $http({
               method: 'GET',
               url: 'http://www.example.com'
            });

        httpPromise.then(function(response){
            // Success promise handling
            // No need for explicit return
        }, function(err){
            // Error promise handling
            // No need for explicit return
        });

        return httpPromise;        
    };        
});

Additionally, it is important to note that return statements within promise resolutions are not necessary. While they can be used for logging purposes, they do not require a return value as the resolution itself is sufficient.

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

A comprehensive guide on accessing attributes of dynamically generated div elements with jQuery

I am currently working on fetching a list of users from a basic MySQL database table named TableA. The table structure includes fields like Username (varchar), Level (tinyint), and DateCreated (datetime). On an HTML page, there is a search input box, let& ...

What's the best approach: Backbone-Relational discovery or retrieval?

Although the model caching feature in Backbone-Relational is effective, loading a simple model securely requires considerable code. For example: // Attempt to locate a model in the cache this.model = MyModel.find({id:id}); if(this.model){ // Model re ...

Nextjs provides separate instances for middleware and api routes, even when using the same singleton class

Here is a utility function that acts as a singleton class to store a counter value. export class CounterSingleton { private static instance: CounterSingleton; private count: number; private constructor() { this.count = 0; } public static ge ...

What are the steps to implement PostgreSQL mod for Vert.x in JavaScript?

Hi there, I'm a newcomer to Vert.x and I am interested in utilizing the https://github.com/vert-x/mod-mysql-postgresql for a particular service. Below is a snippet of code that I am using for my web server: var vertx = require('vertx'); var ...

Does Selenium maintain a cache? I'm confused why my JavaScript doesn't load during the tests

I have a more complicated question, but I am trying to narrow down the issue to avoid any confusion. While testing a page using Selenium, I encountered an anomaly. The page contains two external JavaScript scripts. When visiting the page manually, everyth ...

Traversing a JavaScript object's array using AngularJS

As someone who is brand new to coding, I am embarking on the journey of building a basic website using AngularJS. However, I've hit a roadblock when it comes to looping through an object array in a controller and displaying each item in a directive te ...

How to identify NaN in JavaScript code?

I am attempting to use JavaScript to determine the number of days in a selected month of a selected year. However, I keep receiving a NaN value as a result. How can I resolve this issue? Thank you. <script> function myFunction() { var month ...

Issue with shadows on imported OBJ objects in Three.js when material is applied

After importing an obj using this load function: // triggered when the resource is loaded function ( obj ) { // For any meshes in the model, add our material. obj.traverse( function ( element ) { if ( element instance ...

issue with the remote AJAX call

Hey there! I am currently working with rails 2.3.8 and have run into an issue with a remote form inside a popup. The form uses JavaScript for submitting posts in multipart format. Cool? Here's the partial of the form inside the popup: <script typ ...

Insert the picture into an HTML document and retrieve the image file location

I successfully used <input type="file" accept="image/*"> to upload an image and then applied base64 encoding of the image in the onload callback function of a FileReader instance. However, I encountered a problem when trying to assign this base64 enc ...

What is the best way to pass the value from one textfield to another using material UI in a react application?

I'm looking to transfer the content from a text field in a dialog window to another text field that is not embedded. However, instead of transferring the actual text field value, I'm getting an output of "object Object". Can you help me figure ou ...

Switching from ISO-8859-1 to utf8 with jQuery or JavaScript

One of the APIs I am working with returns text using ISO-88951-1 encoding, causing words with Spanish accents like "obtendá" to be incorrectly displayed as "obtendrá". Is there a way to convert this text to UTF-8? I am looking for a JavaScript or jQ ...

When a React CSS class is deployed to a production server, it may be automatically

I've encountered a strange CSS issue while working on my React project. One specific section of the JSX <div> has a class with style properties defined in the main .css file. During local development, everything appears as expected. However, aft ...

Implementing AJAX in ASP.NET to Dynamically Update Quantities

I own a basket filled with products. I am attempting to boost the quantity by using the (+) button and AJAX. Here is the code snippet: Here is my AJAX code: function addToBasket(id) { var productId = id; var sessionId = Session.SessionID; ...

Executing a script in Mongoose while using Mongodb: A Step-by-Step Guide

When attempting to execute the following script using either the node console or command line, I am encountering issues. What could be causing this problem? const mongoose = require("mongoose"); const ENV = require('dotenv').parse(envStr) mong ...

Stop the anchor from moving around when the page loads

At the moment, I have implemented 'smooth scroll' on my WordPress page. My goal is to achieve a smooth scrolling effect when navigating from an external link by using anchors (e.g., #portfolio). Specifically, I want the page to start at the top a ...

I wonder why serialize() is not returning a response to me

As someone who is just starting to learn jQuery, I've been experimenting with the .serialize method in jQuery. Unfortunately, I haven't had much luck getting it to work properly. Despite connecting to the latest library (version 3.4.1) and checki ...

Autocomplete in Vue.js with cascading suggestions based on object keys

I have been experimenting with creating a 3 or 4 level cascading autocomplete feature in Vue.js, but I'm facing some issues with its functionality. You can view the original code on this CodePen link. <div id="app"> <v-app id=&qu ...

Transferring Element Information to a Bootstrap Modal

Struggling to figure out why the solutions I find are not working for me. It seems like it may be related to my understanding of how elements load in a specific order. I have a common issue - trying to pass data from a button into a modal it triggers. Spe ...

Utilizing various search and filtering methods with Meteor and Mongodb

I am managing a simple collection with fields for name, last name, category, age, and city. I am looking for an efficient way to perform multiple search and filter operations on these elements within a table. For example, filtering by name and age, age and ...