2016-09-19 267 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