angularjs结合$http、$q服务实现多个异步请求

/*在实际业务中经常需要等待几个异步请求完成后进行一下不操作,但是$http不支持同步的请求*/
    angular.module("app", [])
        .controller("ctrl", function ($http, $q) {
            //1.success回调嵌套
            $http({
                url: "data.json",
                method: "get"
            }).success(function (resp) {
                $http({}).success(function (resp) {

                })
            })
            //2.then回调嵌套
            $http({
                url: "data.json",
                method: "get"
            }).then(function (resp) {
                $http({
                    url: "data.json",
                    method: "get"
                }).then(function (resp) {

                })
            })
            //3.$q.all方法第一个参数可以是数组。第一个参数执行完成后执行then方法。
            $q.all({
                first: $http.get("data.json"),
                second: $http.get("data.json")
            }).then(function (arr) {
                console.log(arr)
                angular.forEach(arr,function (value, key) {
                    console.log(value)
                })
            })
        })

你可能感兴趣的:(angularjs结合$http、$q服务实现多个异步请求)