Home > Web Front-end > JS Tutorial > body text

Summary of angularjs methods for handling multiple asynchronous requests_AngularJS

WBOY
Release: 2016-05-16 16:22:00
Original
1139 people have browsed it

In actual business, it is often necessary to wait for several requests to be completed before proceeding to the next step. But $http in angularjs does not support synchronous requests.

Solution 1:

Copy code The code is as follows:

$http.get('url1').success(function (d1) {
           $http.get('url2').success(function (d2) {
​​​​​​ //Processing logic
        });
});

Solution 2:

The methods in then will be executed in order.

Copy code The code is as follows:

var app = angular.module('app',[]);
app.controller('promiseControl',function($scope,$q,$http) {
Function getJson(url){
      var deferred = $q.defer();
$http.get(url)
            .success(function(d){
              d = parseInt(d);
console.log(d);
                   deferred.resolve(d);
            });
          return deferred.promise;
}

getJson('json1.txt').then(function(){
          return getJson('json2.txt');
}).then(function(){
          return getJson('json1.txt');
}).then(function(){
          return getJson('json2.txt');
}).then(function(d){
console.log('end');
});
});

Solution three:

The first parameter of the $q.all method can be an array (object). After the contents in the first parameter are executed, the method in then will be executed. All return values ​​of the first parameter method will be passed in in the form of arrays (objects).

Copy code The code is as follows:

var app = angular.module('app',[]);
app.controller('promiseControl',function($scope,$q,$http) {
$q.all({first: $http.get('json1.txt'),second: $http.get('json2.txt')}).then(function(arr){
console.log(arr);
        angular.forEach(arr,function(d){
console.log(d);
console.log(d.data);
         })
});
});

There are many tutorials on the Internet for detailed usage of $q. I'm new to it too. If you don't speak well, you don't dare to speak nonsense. The above code was written according to my understanding, and it has been tested without any problems.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template