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

"Encountering an error message stating "Cannot access SpreadsheetApp.getUi() within this context" when attempting to execute the

I've encountered an issue while trying to access the UI object in Apps Script. The code I'm using is something I've used before without any problems, but now I'm getting an error message that says "Cannot Call the .getUI()" method from ...

Troubleshooting jsPDF problem with multi-page content in React and HTML: Converting HTML to PDF

I need to convert HTML content in my React application into a PDF file. My current approach involves taking an HTML container and executing the following code snippet: await htmlToImage .toPng(node) .then((dataUrl) => { ...

implementing datepicker on multiple textboxes in jQuery upon button click

I have the ability to show multiple text boxes using jQuery. I am now looking to add a datepicker to those text boxes. Any assistance in finding a solution would be greatly appreciated. Thank you in advance. ...

Tips for verifying that input is provided in a text field when the checkbox is marked

Can someone help me with validating a form where the user must enter data in a text field if they check a checkbox? I have JavaScript code for checkbox validation, but need assistance with text field validation. Thank you! $(document).ready(function () ...

Using es6 map to deconstruct an array inside an object and returning it

I am looking to optimize my code by returning a deconstructed array that only contains individual elements instead of nested arrays. const data = [ { title: 'amsterdam', components: [ { id: 1, name: 'yanick&a ...

Is it possible to dynamically change HTML content by utilizing a JSON file?

Looking to implement a JavaScript loop (using jQuery) that can dynamically populate the HTML file with content from a JSON file based on matching <div> ids to the JSON "id" values. The solution should be scalable and able to handle any number of < ...

Bovine without Redis to oversee queue operations

Can Bull (used for job management) be implemented without utilizing Redis? Here is a segment of my code: @Injectable() export class MailService { private queue: Bull.Queue; private readonly queueName = 'mail'; constructor() { ...

The type '{}' is lacking the 'submitAction' property, which is necessary according to its type requirements

I'm currently diving into the world of redux forms and typescript, but I've encountered an intriguing error that's been challenging for me to resolve. The specific error message reads as follows: Property 'submitAction' is missing ...

ways to dynamically retrieve input values in PHP

Is there a way to dynamically add and remove data fields, as well as increase and decrease fields dynamically in PHP? I am looking to retrieve the subject value in an array or JSON format using PHP only. https://i.stack.imgur.com/HqDCz.png <div data-ro ...

Issue with WebRTC, socket.io, and node.js: Unable to access the property 'emit' as it is undefined

Currently, I am in the process of creating a webrtc video app. Within the client code section, the following lines are present: getUserMedia(constraints, handlemedia, errorhandle); constraints = {video: true}; function handlemedia(stream){ //other act ...

It appears that the use of "window.location" is causing the ajax post

I'm facing an issue with sending data to PHP using AJAX and redirecting to the PHP file. It seems that when I redirect to the PHP file, the data sent through AJAX is not being received. My goal is to have a button click trigger the sending of data to ...

Several validation checks - logic malfunction

I have implemented a validation feature for passwords on a form, but I suspect there may be a logic error in my code that I haven't caught yet (blame it on the coffee machine!). Take a look at the JavaScript below: <script type="text/javascript"& ...

Ensuring the child div's height does not overflow beyond the parent div

When dealing with a parent div and a child div, both having different heights, how can I specifically retrieve the height of the portion of the child div that is within the boundaries of the parent div? Using document.getElementById("id").style.height prov ...

Error: The module 'https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js' is missing the required export 'default'

I'm currently in the process of setting up and testing Google authentication for a web application that I'm developing. Unfortunately, I've encountered several issues with getting the JavaScript functions to work properly, and I am uncertain ...

I have chosen Next.js for my frontend development, while our backend developer is crafting the API in Express and MySQL. I am looking for ways to secure and protect the

As a beginner frontend developer learning Next.js, I've been tasked with integrating authentication into our app. The backend developer is working on creating the API using Express and MySQL. After successful login, an accessToken is received. However ...

ng-class expressions are constantly evolving and adapting

Within a div, I am utilizing ng-class="{minifyClass: minifyCheck}". In the controller, I monitor changes in two parameters - $window.outerHeight and $('#eventModal > .modal-dialog').height(). If there are any changes, I trigger the minifyChan ...

What is the method utilized by Redux to store data?

I am currently developing a small application to enhance my understanding of how to utilize redux. Based on my research, redux allows you to store and update data within the store. In my application, I have implemented an HTML form with two text inputs. Up ...

Drawing intersecting lines on a javascript canvas and clearing them using the lineto method

I am working with a canvas where lines are drawn based on mouse movement. I am trying to achieve the effect of the line only lasting for a few seconds before disappearing, similar to swirling a ribbon with a set length. I have been using lineTo to draw the ...

When the webpage first loads, the CSS appears to be broken, but it is quickly fixed when

Whenever I build my site for the first time, the CSS breaks initially, but strangely fixes itself when I press command + s on the code. It seems like hot reloading does the trick here. During development, I can temporarily workaround this issue by making ...

Choosing a random element in React: A step-by-step guide

I'm currently working on a dynamic website that aims to load a random header component upon each refresh. Despite my various attempts, the functionality operates smoothly during the initial load but consistently throws this error on subsequent refresh ...