javascript AngularJs:$http 同步调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26603532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:12:08  来源:igfitidea点击:

AngularJs: $http Synchronous call

javascriptangularjssynchronous

提问by Erma Isabel

I have a service to for API call as following,

我有一个 API 调用服务,如下所示,

    getValue: function(input) {
        var deferred, url;
        deferred = $q.defer();
        url = "url";
        $http.post(url, input).success(function(data, status, headers, config) {
          return deferred.resolve({
            success: true,
            data: data,
            status: status,
            headers: headers,
            config: config
          });
        }).error(function(data, status, headers, config) {
          return deferred.resolve({
            success: false,
            data: data,
            status: status,
            headers: headers,
            config: config
          });
        });
        return deferred.promise;
      }

But this is async. How can I convert it to sync(I want to make it wait till I get the result)?

但这是异步的。如何将其转换为同步(我想让它等到我得到结果)?

回答by Willem Mulder

No that is not possible with Angular.

不,这在 Angular 中是不可能的。

See https://github.com/angular/angular.js/blob/master/src/ng/httpBackend.js#L51where the XMLHttpRequest is opened with

请参阅https://github.com/angular/angular.js/blob/master/src/ng/httpBackend.js#L51,其中 XMLHttpRequest 使用

xhr.open(method, url, true);

The third parameter in an xhr.open()can be set to falseor true, where false is synchronous and true is asynchronous. In the Angular case, it is hardcoded to true, so that all outgoing calls will be asynchronous.

an 中的第三个参数xhr.open()可以设置为falseor true,其中 false 是同步的,true 是异步的。在 Angular 的情况下,它被硬编码为true,以便所有传出调用都是异步的。

Use the .success()callback to wait until the async call returns, and then do whatever you want to do there.

使用.success()回调等待异步调用返回,然后在那里做任何你想做的事情。

As per the suggestion in the comments, you can of course also do the calls via raw javascript, jQuery or any other library that supports synchronous calls, but I would advise using callbacks/defers with the asynchronous angular call, because synchronous calls are blocking and blocking is bad.

根据评论中的建议,您当然也可以通过原始 javascript、jQuery 或任何其他支持同步调用的库进行调用,但我建议在异步角度调用中使用回调/延迟,因为同步调用会阻塞并且阻塞是不好的。