【问题标题】:AngularJS - Make synchronous http requestAngularJS - 发出同步 http 请求
【发布时间】:2016-12-13 17:38:44
【问题描述】:

角度服务

this.sendCommand = function (someData) {

                URL = myURL;
                return $http({
                    method: 'POST',
                    url: URL,
                    data: someData
                }).then(function (response) {
                    return response.data;
                }).catch(function (error) {
                    console.log(error)
                });
            };

用例:用户可以通过单击一个按钮发送多个命令。例如,在请求 1 响应完成之前,请求 2 不应返回响应。如何使用上面的 sn-p 进行同步调用,这样即使用户多次点击一个按钮,正在发送的请求也会在队列中服务?

【问题讨论】:

  • 为什么用例需要同步请求?
  • @HardikVaghani:$http 函数本身已经返回了一个 Promise 对象。这意味着几乎不需要创建新的 deferred 并将相关的 promise 传回,更不用说将解析和拒绝代码作为服务逻辑的一部分来处理。
  • @zeroflagL:因为接收请求的组件能够一次处理单个请求。
  • 我明白,但请求本身不必是同步的。

标签: angularjs angularjs-http


【解决方案1】:

您可以使用微调器阻止用户在上一个请求完成之前点击按钮。

【讨论】:

    【解决方案2】:

    我认为使用布尔变量可以更好地处理它。由于 javascript 是单线程的,您只需创建一个变量 'isWaitingForResponse' 并添加一个 if 以仅在没有其他正在进行的情况下发送请求。

    this.sendCommand = function (someData) {
        if (!this.isWaitingForResponse) {
            this.isWaitingForResponse = true; 
            // do request
            .then(
                this.isWaitingForResponse = false;
            );
        } else {
            // don't send request
        }
    };
    

    如果您真的想对请求进行排队,您可以使用 javascript:queue stackoverflow queue question。那么您的代码将如下所示:

    this.sendCommand = function (someData) {
        if (!this.isWaitingForResponse) {
            this.isWaitingForResponse = true; 
            // do request
            .then(
                this.isWaitingForResponse = false;
                // check if there is a request in a queue
                // if there is: invoke this.sendCommand
            );
        } else {
            // don't send request
            // put request in a queue
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-22
      • 2011-01-08
      • 1970-01-01
      • 2015-11-21
      • 2018-12-31
      • 2020-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多