函数getIdentityTokenDecrypted
让我很难过。我希望将decryptToken
服务B的承诺退回到getToken
服务A,以便检索令牌。
以下是我需要的步骤:
outlookService.mailbox.getUserIdentityTokenAsync
结果。 (提供加密令牌)$http
路由/api/exchange/createAndValidateIdentityToken
解密令牌。此请求返回SERVICE A中需要的令牌。我怎样才能让它发挥作用?
/*** SERVICE A ***/
var service = {
/*...*/
token: getToken()
};
return service;
function getToken() {
var token;
serviceB.getIdentityTokenDecrypted()
.then(function successCallback(response) {
token = response.data.UniqueUserIdentification;
return token;
}, function errorCallback(response) {
return null;
});
}
/*** SERVICE B ***/
function getIdentityTokenDecrypted() {
var token = null;
var promise;
// This async call does not return a promise,
// I don't think I can chain after it.
outlookService.mailbox.getUserIdentityTokenAsync(function (res) {
token = res;
});
// That's why I use an interval
promise = $interval(function () {
if (token != null) {
$interval.cancel(promise);
return decryptToken();
}
}, 100);
function decryptToken() {
var location = window.location.href;
// I need to get the 'data' from the success
// of this request to retrieve the token
return $http({
method: "POST",
url: "/api/exchange/createAndValidateIdentityToken",
data: JSON.stringify({
userIdentityToken: token,
location: location
})
});
};
return promise;
};
答案 0 :(得分:4)
由于outlookService.mailbox.getUserIdentityTokenAsync
提供回调,因此您不需要$interval
。您可以承诺 - 如果任何异步函数通过创建您自己的承诺(这是不可避免的,这很好)给您回调,然后在您拥有它时从$http
得到的承诺解决它(在你的getUserIdentityTokenAsync
回调被触发之前,你赢了)。
我不做"做" Angular,但显然$q
has a "streamlined" syntax更像ES2015&#39>:
promise = $q(function(resolve, reject) {
outlookService.mailbox.getUserIdentityTokenAsync(function (res) {
if (/*...presumably there's some failure condition...*/) {
reject(/*...*/);
} else {
token = res;
resolve(decryptToken());
}
});
});
(我可能还修改decryptToken
以接受令牌作为参数而不是token
变量。)
关键是,如果您使用另一个承诺解决承诺,那么它将通过链传播。