2016-09-19 265 views
0

我有一個場景,其中一個請求的響應將在響應頭中包含一個令牌,並且我需要將此令牌附加到隨後的任何其他請求。 有什麼建議嗎?同步發送http請求

無法使用承諾,因爲請求的順序沒有定義,可以以任何隨機順序。

下面是我的$ HTTP POST代碼:

var appURL = ''; 
    appURL = serverURL + $backendApis[apiName] + "/?_s=" + $http.defaults.headers.common['Session-Alias']; 

     return $http.post(appURL, postParams).success(function(response, status, headers, config) { 

      $http.defaults.headers.common['Custom-Access-Token'] = headers('Custom-Access-Token'); 
      if (response.errorCode && response.errorCode != "8233" && response.errorCode != "506717") { 
       alert("Sorry, we are not able to provide you a quotation at this stage as we are facing a technical issue. Please get back after sometime to issue a quotation or call us. Sorry for the inconvenience"); 
      } 
     }); 

我只需要等待我的下一個請求開火,直到我沒有得到respons EOF的第一個。 已嘗試使用ajax並將async設置爲false,但不好的部分是它凍結了整個chrome的U.I,給用戶帶來不好的體驗。

在此先感謝。

+0

同步http請求將始終阻止用戶界面,因此無法通過同步請求阻止該請求,因爲您會阻止任何JavaScript執行,直到響應。我相信你應該更好地解釋後來的請求是如何被解僱的,但是一般來說並且只有很少的數據,我相信你可以設置一些互斥體來阻止任何其他http請求觸發,直到完成第一個「主」請求。 – Sergeon

+0

你的意思是'請求的順序未定義'是什麼意思? ..給你的令牌必須是第一個被解僱的人..對嗎? – Disha

+0

@Sergeon能否請你指導我如何設置互斥鎖? – TechHunger

回答

0

這通常是一個壞理念:同步的東西它是異步的「設計」這件事情使你的代碼的味道(如果端點之一是unreacheable它將掛斷你的應用程序?)。

但是,如果出於某種原因,你需要走這條路,你仍然需要使用的承諾,但有一個遞歸方法:

var promises = urls(); //all your urls in an array 

function doCall(){ 

    var appUrl = promises.pop(); 
    $http.post(appURL, postParams).success(function(response, status, headers, config) { 

     $http.defaults.headers.common['Custom-Access-Token'] = headers('Custom-Access-Token'); 
     if (response.errorCode && response.errorCode != "8233" && response.errorCode != "506717") { 
      alert("Sorry, we are not able to provide you a quotation at this stage as we are facing a technical issue. Please get back after sometime to issue a quotation or call us. Sorry for the inconvenience"); 
     } 
    }).then(function(){ 
     if(!promises.length) //no urls left, kill the process. 
      return; 

     doCalls(); //go ahead for the next one 
    }); 
} 

這樣,你就可以以$ HTTP請求同步。

+0

感謝您的答案,但我的問題是,我從任何地方調用此函數,單擊按鈕或任何其他服務調用,所有正在經歷這個函數。有可能是用戶需要一些網址說'登錄'。 。並且不要求其他人說'忘記密碼',反之亦然,所以如果通過你的回答,我將所有Url添加到promise中,那麼promise就永遠不會是空的,它將繼續調用doCalls()。 – TechHunger