[英]How to return a promise from a function?
函數getIdentityTokenDecrypted
給我帶來了getIdentityTokenDecrypted
。 我想從承諾返回decryptToken
服務B來getToken
SERVICE A,檢索令牌。
這是我需要的步驟:
outlookService.mailbox.getUserIdentityTokenAsync
結果。 (提供加密令牌) $http
route /api/exchange/createAndValidateIdentityToken
解密令牌。 該請求返回服務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;
};
由於outlookService.mailbox.getUserIdentityTokenAsync
提供了回調,因此您不需要$interval
。 您可以通過創建自己的Promise(在不可避免的情況下很好),然后用從$http
得到的$http
(直到您的getUserIdentityTokenAsync
回調已觸發)。
我不“做” Angular,但是顯然$q
具有“簡化的”語法 ,就像ES2015那樣:
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
變量。)
關鍵在於,如果您用另一個承諾解決一個承諾,則該保證會在整個鏈中傳播。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.