Is it possible to return a promise after utilizing .then() in AngularJS?

As someone who is still getting the hang of Angular and promises, I want to make sure I'm on the right track.

Right now, my data layer service uses Restangular to fetch data and returns a promise. Here's how it looks...

dataStore.getUsers = function (params) {
    return users.getList(params);
};

The controller that calls this function receives a promise in response like this...

$dataStore.getUsers(params).then(function (response) {
    $scope.users = response;
}, function(response) {
    $log.error("There was an error fetching users: ", response);
});

While this setup is working fine, I want to handle the promise within my datastore before sending it back. I'd like to use the .then() method to check for errors and log them. Then, from both the success and failure functions, I want to return the original promise back to the controller.

I don't want to change any code in my controller; I just want to modify my datastore code. Here's some simplified code to illustrate what I'm aiming for...

dataStore.getUsers = function (params) {

    users.getList(params).then(function (response) {
        $log("Server responded")
        return original promise;
    }, function(response) {
        $log.error("Server did not respond");
        return original promise;
    });

};

Answer №1

Your approach in the pseudo code was actually quite close to the correct solution. In order to chain promises, you can modify your code like this:

dataStore.getUsers = function (params) {
    return users.getList(params).then(function (response) {
        $log("server responded")
        return response;
    }, function(failure) {
        $log.error("server did not respond");
        // change to throw if you want Angular lever logs
        return $q.reject(failure); 
    });

};

Now, the controller will be resolved or rejected with the same value. Remember that you need to tap into the promise using a .then handler to manage it. While other libraries have convenience methods for this, $q is more minimalistic.

Another option is to use the catch syntax for cleaner code and also log any errors:

dataStore.getUsers = function (params) {
    return users.getList(params).then(function (response) {
        $log("server responded")
        return response;
    }).catch(function(failure) {
        $log.error("server did not respond");
        throw failure;
    });

};

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

Differences in Function Scope: A Comparison of ECMAScript 6 and ECMAScript 5

What are the advantages of ES6 compared to ES5 when it comes to block scope functions? Although the blocks may look similar in both cases, what impact does it have performance-wise and which approach is more efficient? ES6 Block { function fo ...

Ensuring Filesize Verification Prior to Upload on Internet Explorer Using Javascript

Can JavaScript be used to verify a file's size before it is uploaded to the server at the client side? This application is developed using EXTJS and Java and is limited to Internet Explorer 7 on Windows XP machines. ActiveX cannot be used. The workf ...

Utilizing AngularJS: Implementing a directive to invoke a controller function with parameters

One concept I am already familiar with involves calling a controller function without arguments inside a directive. The following code demonstrates this: Firstly, in the directive definition: scope: { actionFunc: "&" } Within the directive template: ...

What is the method for invoking an express middleware function that triggers a file download?

Currently, I am delving into Express and experimenting with middleware. My goal is to initiate a file download when accessing the root route while sending out a "Hello World" message. My attempts so far have been: function initiateDownload(req, res, next) ...

The rsuite table does not properly reflect changes in state data

This is the render method that I am working on render() { return ( <Contentbox> <ol> {this.state.data.map((obj) => ( <li key={obj._id}>{obj.name}</li> ) ...

Retrieve the current element when the key is released and send it as a parameter to a different function

Imagine a scenario where my website contains textbox elements that are dynamically generated, each with the class 'mytxt'. <input type="text" class="mytxt" /> <input type="text" class="mytxt" /> <input type="text" class="mytxt" /& ...

Looking to show an image when a checkbox is ticked and hide it when it is unticked in HTML?

How do I make a specific image appear when a user clicks on a checkbox? I'm unsure if I should use jQuery, Ajax, or another method. What is the best approach for this task? Your assistance would be greatly appreciated. I have successfully created the ...

Generating CSV headers for all nested objects in JavaScript

Utilizing the "react-json-to-csv" library to convert my JSON data into a CSV file has presented an issue with nested objects. The CSV export header is breaking, displaying alternate data because of these nested objects. Here's an example of my JSON da ...

The 'userEvent.type' function in React Testing Library is failing to update the input value in a Material UI TextField component that has

I am currently facing an issue with a material UI TextField element that is meant to track the latitude value. The requirement is for the latitude to fall within the range of -90 to 90 degrees. I have implemented a unit test as a validation measure, howeve ...

I encountered a parsing issue while trying to compile my Vue project

Issue: The component name "Header" should always consist of multiple words. Fix: Change the component name to a multi-word format according to Vue standards (vue/multi-word-component-names). ...

What is the best way to enclose a block of content with <div> and </div> tags using the append() function?

My goal is to add an outer div container by first appending it, then adding content, and finally appending the closing tag. However, I'm encountering an issue where the div I added at the beginning automatically closes itself, resulting in two separat ...

Clicking on an item will now automatically remove it from the selection, rather than requiring you to click on a specific

Is there a way to customize the design of select2 items in a multi-select box so that users can easily remove selected items by clicking anywhere on the button, rather than just the small "cross" icon on the left-hand side? Refer to the image; instead of n ...

Extract JSON data from a zipped file using adm-zip

Trying to extract and parse a JSON file named manifest.json from the root of a zip archive has been my current challenge. Regardless of the specific zip file being processed, the JSON file will always be named manifest.json. Presently, this function is w ...

Client-side validation with Jquery is failing to function properly

Currently, I am experimenting with the jquery.validate.unobtrusive.js plugin to dynamically generate form fields. Here is an example of how I'm creating a textarea field: var message = $("<textarea id='test'></textarea>"); $(mes ...

The planebuffergeometry does not fall within the three namespace

I am currently working on a project using three.js and next.js, but I keep encountering this error: 'planeBufferGeometry is not part of the THREE namespace. Did you forget to extend? See: As a beginner in three.js, I'm unsure what exactly is ca ...

Can you provide some insight into why the init() method is throwing an error?

My project utilizes DynamoDB access through https://www.npmjs.com/package/react-native-dynamodb. I followed the code provided on the website for implementation. The issue I'm facing is that when hovering over my .init() method in WebStorm IDE, it sho ...

How to Use Radio Buttons in Material-UI to Disable React Components

Just starting out with ReactJS and Material-UI, I've been experimenting with them for about 3 weeks. Currently, I'm facing a challenge where: - There are 2 radio buttons in a group and 2 components (a text field and a select field); - The goal is ...

The issue arises due to conflicting indent configurations between eslint and @typescript-eslint/indent

Currently, I am using eslint and prettier in a TS express application. I am trying to set the tab width to 4, but it appears that there is a conflict between the base eslint configuration and the typescript eslint. When looking at the same line, this is w ...

Encountering problems when trying to display two lines using JSON data on Highcharts in AngularJS - name not defined

Trying to dynamically plot a high chart using Angular JS. I have two lines that I want to show on the same graph. An example item in the 'jsondata' is: { "ID": 123456, "SaleDate": "2016-02", "SalesAgeBuck ...

What could be the reason for the variable not resetting in my event handler?

Check out the code I've written below: $(document).ready(function () { var default_var = 2; var show_var = default_var; var total_var = 8; var increment_var = 2; var start_var = show_var+1; var end_var = show_var+increment_v ...