Marco Santos
Marco Santos

Reputation: 1001

Combining 2 promises in angularjs

Im combining 2 promises but isnt working, in a service i have 2 methods, where the method "UserService.getAuthenticatedUser()" gets the current user information and than there is a "UserService.getAccountTypeData(idUser)", where gets the usertype information, but to get to the second method i need the userID, so basically first i call the "UserService.getAuthenticatedUser()", get the id, and than call "UserService.getAccountTypeData(idUser)", but isnt working.

 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 already injected the service...

Upvotes: 0

Views: 42

Answers (2)

Zach
Zach

Reputation: 3207

You're dealing with asynchronous calls, so when you call the .then() method, it's executing the function and wiring up the callback to an anonymous function passed as a parameter to then(). If the second is dependent on the first, you could nest them like this...

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

Upvotes: 0

SteamDev
SteamDev

Reputation: 4414

You can chain your promises by returning values from your .then() functions.

function isAccount(accountName) {
    return UserService.getAuthenticatedUser(accountName) // pass in accountName argument?
        .then(function(response) {
            var userDetails = response.data;
            return userDetails.Id; // user id value
        })
        .then(UserService.getAccountTypeData) // userDetails.Id gets passed to getAccounttypeData method
        .then(function(response) {
            var userDetails = response.data;
            return userDetails;
        });

}

// usage
isAccount('AccountA').then(function(userDetails) {
    // do something with userDetails
});

Upvotes: 2

Related Questions