javascript - 是否使用 Promise 或通过 $http 调用延迟

标签 javascript angularjs ionic-framework

我无法弄清楚我的代码应该使用什么以及如何使用 promise 。通过我的 $http 调用。

我有以下功能

首先我想打电话

$scope.getAcessToken()

一旦我获得访问 token ,我将进行以下调用

$scope.getDataSets(lastSaved, cTime, accessToken)

两个函数如下:

$scope.getAcessToken = function()
  {
    alert("inside getAcessToken function");
    refreshToken = localStorage.getItem("refreshToken");
    if(refreshToken)
    {
      $http({
            method: "post", url: "https://accounts.google.com/o/oauth2/token", 
            data: "client_secret=" + clientSecret + "&grant_type=refresh_token" + "&refresh_token="+ refreshToken + "&client_id=" + clientId  
              })
      .success(function(data){
            accessToken = data.access_token;
      })
      .error(function(data,status){
        alert("ERROR: " + JSON.stringify(data) + status);
      });
    }
    else
    {
      $scope.firstTimeAuth();
    }
    return accessToken;
  }

$scope.getDataSets = function(startTime, endTime, accessToken, )
  {
    $scope.a = "inside dataSets function";
    $url = "https://www.googleapis.com/fitness/v1/users/me/dataSources/derived:com.google.step_count.delta:com.google.android.gms:estimated_steps/datasets/" + startTime +"000000"+"-"+ endTime + "000000"; 
    alert("acess token is " + accessToken );
    if(accessToken != "")
    {
        $http({method: 'GET', url: $url,
                        headers: {'Authorization': 'OAuth ' + accessToken},               
            })
            .success(function(response){
                alert("inside success block datasets");
                $scope.handleResponse(response);
            })
            .error(function(response) {
                alert("Something went wrong" + JSON.stringify(response));
            });
        }
        else
        {
            alert("no access token received");
        }
  }

因此,在我实际获得访问 token 之前,获取数据集会被执行 如何预防? 编辑1:

$scope.firstTimeAuth = function(callback) {
      var ref = window.open('https://accounts.google.com/o/oauth2/auth?client_id=' + clientId + '&redirect_uri=http://localhost/callback&scope=https://www.googleapis.com/auth/fitness.activity.write &approval_prompt=force&response_type=code&access_type=offline', '_blank', 'location=no');
      ref.addEventListener('loadstart', function(event) {

        if((event.url).startsWith("http://localhost/callback")) {
            requestToken = (event.url).split("code=")[1];

            $http({
                method: "post", url: "https://accounts.google.com/o/oauth2/token", 
                data: "client_id=" + clientId + "&client_secret=" + clientSecret + "&redirect_uri=http://localhost/callback" + "&grant_type=authorization_code" + "&code=" + requestToken 
              })
              .success(function(data) {
                      accessToken = data.access_token;
                      refreshToken = data.refresh_token;
                      if(typeof(Storage) != "undefined") {
                          localStorage.setItem("refreshToken", refreshToken);
                          alert(localStorage.getItem("refreshToken"));
                      } else {
                          alert("Sorry, your browser does not support Web Storage...");
                      }
                      //$location.path("/secure");
                  })
               .error(function(data, status) {
                      alert("ERROR: " + data);
                  });
              ref.close();
          }
      });
      callback();
  }

最佳答案

您必须在 $scope.getAcessToken 函数中使用 defer 来使整个函数成为一个 promise 。为了使其正常工作,您需要在 Controller 依赖项中添加 $q 。您的函数现在将如下所示:

$scope.getAcessToken = function(){
        alert("inside getAcessToken function");
        refreshToken = localStorage.getItem("refreshToken");
        var deferred = $q.defer();
    if(refreshToken){
          $http({
                method: "post", url: "https://accounts.google.com/o/oauth2/token", 
                data: "client_secret=" + clientSecret + "&grant_type=refresh_token" + "&refresh_token="+ refreshToken + "&client_id=" + clientId  
                  })
          .success(function(data){
                accessToken = data.access_token;
                deferred.resolve(true);
          })
          .error(function(data,status){
               alert("ERROR: " + JSON.stringify(data) + status);
               deferred.resolve(true);
          });
        }
        else
        {
          $scope.firstTimeAuth();
        }
        return deferred.promise;
      }

现在您可以将此函数用作 promise ,以便在完成后调用 $scope.getDataSets

$scope.getAcessToken().then(function(){
    $scope.getDataSets();
});

关于javascript - 是否使用 Promise 或通过 $http 调用延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37340776/

相关文章:

css - Ionic 2 如何使 ionic 列表从下往上增长?

ios - Xcode 版本 10.3 ITMS-90035 : Invalid Signature

javascript - jquery中如何将json输出转换为数组

Javascript 窗口未定义

javascript - 基于单击按钮在 Div 中呈现新 View | AngularJS

javascript - 定时器的 Angular Directive(指令)到指令通信

ionic-framework - IONIC 2 ionic 选择更改时隐藏和显示文本框

javascript - 淡出所有 "LI"元素

angularjs - HTTP 请求已被阻止;内容必须通过 HTTPS 提供

javascript - 单击链接时 Angular 隐藏内容