我有一个返回字符串值的子函数,它驻留在父函数中。我知道GetEncCreds
函数有效,因为下面返回的警报确实正确返回了credString
值。我遇到的问题是,当我从另一个函数调用此函数GetEncCreds
时,我的encCreds
变量是undefined
。我不确定如何将结果传递给父函数?
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');
}
答案 0 :(得分:3)
修改服务以返回承诺:
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;
}
从承诺中提取数据:
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);
})
}
Promise的.then
方法返回新的Promise ,该新的Promise通过successCallback
,errorCallback
的返回值来解决或拒绝(除非该值是一个承诺,在这种情况下,它将使用promise chaining来解决该承诺中所解析的值。
有关更多信息,请参见