如何使用 $q 将金字塔请求更改为承诺
How to change pyramid request to promises with $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");
});
});
});
});
}
我以前从没用过$q。
所以最佳做法是从控制器中提取 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
});
});
}]);
我想将此金字塔请求更改为带有 $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");
});
});
});
});
}
我以前从没用过$q。
所以最佳做法是从控制器中提取 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
});
});
}]);