如何用$q将金字塔请求更改为承诺



我想把这个金字塔请求改成$q的承诺。

app.controller('Ctrl', function ($scope, $http, $q) {
$http.post('http://localhost:1235',data_post1).success(function (data){
    console.log("1");
    $http.post('http://localhost:1236',data_post2).success(function (data){
        console.log("2");
        $http.post('http://localhost:1237',data_post3).success(function (data){
            console.log("3");
            $http.post('http://localhost:1238',data_post4).success(function (data){
                console.log("4");
            });
        });    
    });
});
}

所以最佳实践是将HTTP请求从控制器中拉出

如果你有一个像

这样的工厂
app.factory("fooSrvc", ["$q", "$http", function($q, $http){
    return {
        data1: function(postData){
            var deferred = $q.defer();
            $http.post("", postData).success(function(results){
                deferred.resolve(results);
            });
            return deferred.promise;
        },
        data2: function(postData){
            var deferred = $q.defer();
            $http.post("", postData).success(function(results){
                deferred.resolve(results);
            });
            return deferred.promise;
        }
    };
}]);

那么你的控制器就可以变成

app.controller("Ctrl", ["$scope", "fooSrvc", function($scope, fooSrvc){
    fooSrvc.data1(dataTopost).then(function(results){
        // do something with it here possibly
        fooSrvc.data2(moreDataToPost).then(function(moreResults){
            // do something with it here possibly
        });
    });
}]);

最新更新