1

I have a child function that returns a string value, and it resides in a parent function. I know the GetEncCreds function works, because the alert returned below does return the credString value correctly. The problem I am having is when I call this function GetEncCreds from another function, my encCreds variable is undefined. I'm not sure how to pass my result up to the parent function?

function GetEncCreds(domain, userName, password){
        var credString = "";
       genCredApi.save({
            domain: domain,
            userName: userName,
            password: password
        }).$promise.then(function (result){
           credString = result.Credentials;

          //This below alert works
           alert(credString);
           return;

        })

        return credString;

    }

function onRdsAssociatedDocsClicked() {
        var encCreds = GetEncCreds('ax-rds', 'axadmin', 'Pa$$word');
}
georgeawg
  • 48,608
  • 13
  • 72
  • 95
MikeGen18
  • 49
  • 7

1 Answers1

3

Modify the service to return a promise:

function GetEncCreds(domain, userName, password){
   var credString = "";
   ̶g̶e̶n̶C̶r̶e̶d̶A̶p̶i̶.̶s̶a̶v̶e̶(̶{̶
   var promise = genCredApi.save({
        domain: domain,
        userName: userName,
        password: password
    }).$promise.then(function (result){
       credString = result.Credentials;
      //This below alert works
       alert(credString);
       ̶r̶e̶t̶u̶r̶n̶;̶
       return credString;
    })
    ̶r̶e̶t̶u̶r̶n̶ ̶c̶r̶e̶d̶S̶t̶r̶i̶n̶g̶;̶
    return promise;
}

Extract the data from the promise:

function onRdsAssociatedDocsClicked() {
    ̶v̶a̶r̶ ̶e̶n̶c̶C̶r̶e̶d̶s̶ ̶=̶ ̶G̶e̶t̶E̶n̶c̶C̶r̶e̶d̶s̶(̶'̶a̶x̶-̶r̶d̶s̶'̶,̶ ̶'̶a̶x̶a̶d̶m̶i̶n̶'̶,̶ ̶'̶P̶a̶$̶$̶w̶o̶r̶d̶'̶)̶
    var promise = GetEncCreds('ax-rds', 'axadmin', 'Pa$$word');
    promise.then(function(data) {
        var encCreds = data;
        console.log(encCreds);
    })
}

The .then method of a promise returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback (unless that value is a promise, in which case it is resolved with the value which is resolved in that promise using promise chaining.

For more information, see

georgeawg
  • 48,608
  • 13
  • 72
  • 95