Is it possible to return a promise within the .then function in AngularJS?

I have a unique service called "usersService". I want to create a special method that interacts with another custom service I built. This other service has two handy methods: getUser() and getCurrentUser(). The getCurrentUser() method relies on the injected service to fetch the User ID (UID), which is then used to execute the getUser() method. My main challenge is figuring out how to return the nested promise from the getCurrentUser() method.

Explaining this question can be a little tough, but here's the one-of-a-kind code...

svs.service("usersService", function($rootScope, $http, loginService, alertBoxService) {
  var self = this;
  self.getUser = function(identifier, column) {
    if (typeof(column) === 'undefined') column = "uid";
    return $http.get($rootScope.api + "/getUser/" + identifier + "/" + column);
  }
  self.getCurrentUser = function() {
    var currentUserPromise;
    loginService.getCurrentUid().then(
      function(response) {
        if (response.data === "false") {
          alertBoxService.trigger($rootScope.unexpectedApiResponse);
        } else {
          console.log(self.getUser(response.data));
          currentUserPromise = self.getUser(response.data);
        }
      }, function(response) {
        alertBoxService.trigger($rootScope.asyncFailed);
      }
    );
    return currentUserPromise;
  }
});

Answer №1

Remember to chain both promises and rejections when working with promises...

self.fetchUser = function() {
    return authService.getCurrentUser().then(function(result) {
        if (result.data === 'false') {
            notificationService.showAlert($rootScope.unexpectedApiResponse);
            return $q.reject(result); // transforming it into a rejection
        }
        return self.getUserData(result.data); // chaining the promise resolution
    }, function(result) {
        notificationService.showAlert($rootScope.asyncFailed);
        return $q.reject(result); // chaining the rejections
    });
}

Don't forget to inject the $q service.


As mentioned by Susan in her comment, you can also reject the promise by throwing an error instead of using $q.reject. For example:

throw result;

Answer №2

One issue lies in the fact that when the function getCurrentUser is invoked, it promptly yields an undefined variable. This arises due to the asynchronous nature of the service, causing the function call to have already returned an undefined variable before the response is received. To circumvent this, you can include the return statement within the loginService.

Answer №3

When dealing with async functions, it is important to understand how to properly handle promises in order to provide the desired result. In this case, you need to return a promise from the success callback by returning the promise object itself and then return that same promise from the main function to make it accessible to the caller.

To accomplish this, give this approach a try:

  svs.service("usersService", function($rootScope, $http, loginService, alertBoxService) {
  var myself = this;
  myself.fetchUser = function(identifier, column) {
    if (typeof(column) === 'undefined') column = "uid";
    return $http.get($rootScope.api + "/getUser/" + identifier + "/" + column);
  }
  myself.getCurrentLoggedInUser = function() {
    return loginService.getCurrentUser().then(
      function(response) {
        if (response.data === "false") {
          alertBoxService.trigger($rootScope.unexpectedApiResponse);
        } else {
          console.log(myself.fetchUser(response.data));
          return myself.fetchUser(response.data);
        }
      }, function(responseError) {
        alertBoxService.trigger($rootScope.asyncFailed);
      }
    );
  }
});

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

Unpacking nested objects using dynamically generated property names in a React state - a guide

Having trouble with using setState and figuring out how to destructure the object with a dynamic property name, denoted by id. The state looks like this after computation: { "inputConfig": { "5d4d684cadf8750f7077c739": { "0": "5d4d ...

My components views are not being rendered in Angular 4

Currently, I am in the process of learning how to use Angular 4, but I seem to be encountering an issue. Despite having a functioning App template that renders perfectly fine, I am facing difficulties when attempting to render more than one template. I cre ...

Responsive Bar Chart using jQuery Mobile and ChartJS that appears on the screen only after resizing

I have been experimenting with adding a responsive bar chart using Chart.js in one of my JQM projects. Here is what I have accomplished so far: http://jsfiddle.net/mauriciorcruz/1pajh3zb/3/ The Chart needs to be displayed on Page Two and it should be res ...

Searching for a solution on how to retrieve data server-side in the newest version of Next.js? Attempted to use getStaticProps but encountering issues with it not executing

Currently tackling a project involving Django Rest Framework with Next.js, and encountering a roadblock while trying to fetch data from the API. Data is present at the following URL: http://127.0.0.1:8000/api/campaigns, visible when accessed directly. The ...

Determining the client web app version in HTTP requests

We frequently update our single page application, but sometimes an older version with a bug can still be in use. It would be helpful if the client could include a version identifier with requests to let us know which code base is being used. Are there est ...

How to create a basic calculator in AngularJS with two textboxes specifically designed for calculating squares?

My code snippet is as follows: <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body> <div ng-app="app"> <div ng-controller="Calcu ...

Guide to converting a specific tag into div using Javascript

I am working with some HTML code that includes a div: <div class="myDiv"> <a href="" title="">My link</a> <p>This is a paragraph</p> <script>//This is a script</script> </div> Additionally, I ha ...

What could be causing my fetch() function to send a JSON body that is empty?

I've been struggling with sending JSON data using fetch as the backend keeps receiving an empty object. In my Client JS code, I have the following: const user = "company1"; const username = "muneeb"; const data = {user, username}; fetch("http://127. ...

Can someone guide me on the process of opening and closing a Material-UI Dialog within a Meteor/React application?

I'm attempting to create a dialog with a form that pops up when the user clicks a button. I followed the example on the Material-UI Dialog site for creating a button to open the dialog and adding a TextField within it. This is being done using Meteor ...

Exploring the possibilities with a Nuxt Site as a foundation

[![enter image description here][1]][1] Exploring the world of nuxt and vue, I aim to build a basic website using vue and then convert it into a static site utilizing: nuxt generate I have successfully accomplished this task with nuxt and vuetify (check ...

Tips on selecting the active color ID from a list of available color IDs

Currently, I am trying to retrieve the color ID of the active color selection. For example, if I have three colors - yellow, blue, and red - with yellow being the default color. In this scenario, I can obtain the color ID of yellow using a hidden input typ ...

Migration of old AngularJS to TypeScript in require.js does not recognize import statements

I am looking to transition my aging AngularJS application from JavaScript to TypeScript. To load the necessary components, I am currently utilizing require.js. In order to maintain compatibility with scripts that do not use require.js, I have opted for usi ...

Unable to send multiple cookies using custom headers in Next.js configuration

I am using custom headers to set the cookie in my next.config.js file. The refresh token is successfully set, but for some reason the second token is not being recognized. key: 'Set-Cookie', value: `RefreshTokenKey = " ...

Struggling with passing the decoded user ID from Node Express() middleware to a route can be problematic

I have encountered a similar issue to one previously asked on Stack Overflow (NodeJS Express Router, pass decoded object between middleware and route?). In my scenario, I am using the VerifyOrdinaryUser function as middleware in the favorites.js route. Th ...

Utilize the splice function when resizing the window based on specific breakpoints

On a series of div elements, I have implemented some JS/jQuery code that organizes them by wrapping every three elements in a container with the class .each-row. <div class="element"></div> <div class="element"></div> <div class ...

The function '.save' is not recognized by Mongoose

As a newcomer, I have been trying to understand the code in this calendar app that I created using express-generator. Everything seems to be working fine with connecting to MongoDB, but I am facing issues when trying to save a document. The section of my ...

The jQuery Select2 Plugin for Dynamic Dropdowns with Ajax Integration

Utilizing the Select2 plugin with Ajax to connect to my employee database has been quite helpful. It allows setting up a meeting and selecting all the employees you wish to invite. Here is an example of the code: $("#requiredAttendees").select2({ ...

Tips on creating a unique d3js tree design

I am a beginner when it comes to d3js and javascript in general. My goal is to create an interactive IP administration overview using d3js by modeling json data. I know that the key tool for this job is likely d3.layout.tree, which will provide me with the ...

Getting the value of a JavaScript variable and storing it in a Python variable within a Python-CGI script

Is there a way to capture the value of a JavaScript variable and store it in a Python variable? I have a Python-CGI script that generates a selection box where the user can choose an option from a list. I want to then take this selected value and save it ...

A step-by-step guide on how to render a view in AngularJS only after the model

Is there a way to delay loading my view in AngularJs until after my modal is fully prepared? I want to avoid using the $timeout function. Currently, when I launch the page, it appears blank at first and then gradually loads with the data. Any suggestions ...