如何从函数中返回一个promise?

时间:2015-10-19 15:37:49

标签: javascript angularjs promise

函数getIdentityTokenDecrypted让我很难过。我希望将decryptToken服务B的承诺退回到getToken服务A,以便检索令牌。

以下是我需要的步骤:

  1. 获取outlookService.mailbox.getUserIdentityTokenAsync结果。 (提供加密令牌)
  2. 通过$http路由/api/exchange/createAndValidateIdentityToken解密令牌。此请求返回SERVICE A中需要的令牌。
  3. 我怎样才能让它发挥作用?

    /*** 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;
    };
    

1 个答案:

答案 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变量。)

关键是,如果您使用另一个承诺解决承诺,那么它将通过链传播。