Bringing together two commitments in angularjs

I am facing an issue while trying to combine 2 promises in a service. I have 2 methods - one is "UserService.getAuthenticatedUser()" which fetches the current user information, and the other is "UserService.getAccountTypeData(idUser)" which retrieves the user type information. However, in order to access the second method, I need the userID. So essentially, I first call "UserService.getAuthenticatedUser()" to get the id, and then call "UserService.getAccountTypeData(idUser)", but it's not working as expected.

 function isAccount(accountName) {
             UserService.getAuthenticatedUser()
                .then(function (response) {
                    var userDetails = response.data;

                });


            UserService.getAccountTypeData(idUser)
                .then(function (response) {
                    var userDetails = response.data;
                    return  userDetails;
                });

}

PS: I have already injected the service...

Answer №1

To create a chain of promises, you can return values from each of your .then() functions.

function checkAccountValidity(accountName) {
    return UserService.getAuthenticatedUser(accountName) 
        .then(function(response) {
            var userDetails = response.data;
            return userDetails.Id; 
        })
        .then(UserService.getAccountTypeData) 
        .then(function(response) {
            var userDetails = response.data;
            return userDetails;
        });

}

// implementation
checkAccountValidity('AccountA').then(function(userDetails) {
    // utilize userDetails in some way
});

Answer №2

When handling asynchronous calls, the .then() method is key. It executes the function and links up the callback to an anonymous function passed as a parameter to then(). If the second call relies on the outcome of the first, you can nest them as shown below...

function checkAccount(accountName) {
      UserService.getAuthenticatedUser()
         .then(function (response) {
             var userDetails = response.data;
             UserService.getAccountTypeData(idUser)
                .then(function (response) {
                    var userDetails = response.data;
                    return  userDetails;
                });
         });
}

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

Executing a function in JavaScript using square brackets

While I was reading through the jQuery source code, I came across this interesting line: jQuery(this)[ state ? "show" : "hide" ](); Is there any particular benefit to using this syntax over the more traditional approach shown below? state ? jQuery(this) ...

Organize nested level components in react native into a more structured order

Currently, I am working with some JSON data that has the following structure: const data = { "stores": [ { "name": "s1", "id": "6fbyYnnqUwAEqMmci0cowU", "customers": [ { "id": "4IhkvkCG9WWOykOG0SESWy", ...

Is it possible to showcase content when double curly brackets are nested within another set of double curly brackets

Having this specific case, I am interested in showcasing information from the model. Is it possible to utilize double curly braces within another set of double curly braces? ...

How can I handle moving to button code-behind when validation fails without relying on Page.IsValid?

Recently, I encountered a challenge with an ASP.NET page that contains both ASP.NET validators and JavaScript checks. As I delved into the button code behind the scenes: protected void Button2_Click(object sender, EventArgs e) { if (Page.IsVal ...

Troubleshooting: Issue with onclick event in vue.js/bootstrap - encountering error message "Variable updateDocument not found"

As a newcomer to frontend development, I have a basic understanding of HTML5, CSS, and Javascript. Recently, I started working on a vue.js project where I integrated bootstrap and axios. Everything seemed to be working fine until I encountered an issue whe ...

Cyrillic characters cannot be shown on vertices within Reagraph

I am currently developing a React application that involves displaying data on a graph. However, I have encountered an issue where Russian characters are not being displayed correctly on the nodes. I attempted to solve this by linking fonts using labelFont ...

Count the number of checkboxes in a div

In my current project, I am working on incorporating three div elements with multiple checkboxes in each one. Successfully, I have managed to implement a counter that tracks the number of checkboxes selected within individual divs. However, I now aspire to ...

React component failing to update when props change

After loading correctly, my react component fails to re-render when props change. Despite the fact that render() is being called and the list array contains the correct data according to console.log(list), the page does not refresh. Adding a setState in co ...

Detecting when a directive element has not been clicked in Angular may involve checking for certain event behaviors

I am looking to enhance the functionality of the "deselect" feature in multiple directives like buttons and popovers. Specifically, I want my functions to activate when the user clicks on an element that is not part of the directive template. Currently, I ...

Determine the exact width of text without rounding in Javascript

I'm facing an issue with a div element that I'm manipulating using Javascript to change its position. The problem is that it's rounding off incorrectly. #hi{ background-color: blue; width: 2px; height: 10px; position: absolu ...

Having trouble with data retrieval from MySQL using PHP and Angular on certain mobile devices, although it functions properly on desktops and laptops

The data retrieved from the mysql database is functioning properly on desktop and laptop, but not on mobile devices. The following HTML code is present in the html file: <table class="table table-default"> <thead> <tr> & ...

AngularJS ngTable Error Detected

When using ngTable (AngularJS) to display a list of elements, an error arises during compilation: ************ I am OK ****************** articles.client.controller.js:12 ReferenceError: articles is not defined at new (...../modules/articles/controlle ...

Using AJAX to send data to the server in jQuery

Currently, I have an AJAX request implemented on my webpage. I am exploring methods to detect when an AJAX call is initiated within the page using jQuery or JavaScript. Is there a way to identify or trigger a function upon the initiation of an AJAX reques ...

Spinner loading animation not showing correctly

Even though it shows up when I hover over and inspect, the image remains completely invisible. It's saved in the same folder and I believe all the file names are correct, but for some reason, it's just not working as expected. Any help would be g ...

Attempting to replace the checkbox image resulted in no changes

<?php require 'includes/configs.inc.php'; ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title><?php $site_name ?></titl ...

Clicking within the text activates the dropdown menu, but clicking outside the text does not

My custom drop down menu is not functioning properly. When I click on the text, it successfully links to another place, but when I click beside the text, it does not link. Can you please help me identify what's wrong here? Your assistance would be gre ...

Generate a new dynamic page in ASP.NET C# eCommerce platform whenever a user posts their item

Currently, I am in the process of building a website similar to eBay where users can list their own items for sale. My main concern is ensuring that each time a user posts an item on our site, a new link or page will be automatically generated. The same go ...

Experiencing difficulties establishing a connection between the React client and Node.js server using SocketIO

I am currently getting familiar with socketIO and have successfully set up a basic nodejs server. However, I am facing an issue where my nextJS app is unable to connect to the server as expected. Despite no errors being displayed, the messages that should ...

Aligning the stars with CSS

One of the components I have deals with a star rating system, and I thought it would be cool to use Font Awesome icons for half stars. Everything is working well except for the CSS styling aspect. While I managed to position some of the stars correctly by ...

When attempting to submit a record at http://localhost:5173/, a 404 (Not Found) error was

Currently, I am attempting to retrieve username data and timeTaken from a form. My goal is to send this data to my server, create the User object, and store it in MongoDB Atlas. Unfortunately, I am encountering a 404 error that I am struggling to resolve. ...