[英]Angular Promise not running synchronously
我的JavaScript控制器中包含以下代碼。 這些功能在從視圖中獨立或異步調用時起作用。 但是我想在頁面加載時同步調用它們,因為第二個函數的調用中使用了第一個函數的返回值
$scope.function1= function () {
$http({
url: '/Class/method1/',
method: 'GET'
}).success(function (data) {
$scope.mygrid= data.data;
$scope.myvalue= $scope.mygrid[0];
});
};
$scope.function2= function () {
$http({
url: '/class/method2/',
method: 'POST',
params: { myValue: $scope.myvalue }
}).success(function (data) {
$scope.myValue2 = data.data;
});
};
var initialize = function () {
var defer = $q.defer();
defer.promise
.then(function() {
$scope.function1();
})
.then(function() {
$scope.function2();
})
defer.resolve();
};
initialize();
在第二次調用中,$ scope.myvalue為空。 數據已從函數1返回,所以我唯一想到的就是function2的調用時間過早。 有指針嗎? :-)
initialize
的promise同步運行。 雖然$http
請求沒有。 這導致調用$scope.function2
不必等待一個承諾$scope.function1
來解決。
它應該是
$scope.function1= function () {
return $http...
};
$scope.function2= function () {
return $http...
};
在這種情況下,deferred promise 是antipattern ,並且initialize
應該像這樣簡潔:
var initialize = function () {
return $scope.function1().then(function() {
return $scope.function2();
})
};
$http({
url: 'url',
method: 'GET'
})
這也是一種承諾,因此它將異步運行。
$scope.function1= function () {//3rd step
$http({
url: '/Class/method1/',
method: 'GET'
}).success(function (data) {
$scope.mygrid= data.data; //this run as asyn after response recived
$scope.myvalue= $scope.mygrid[0];
});
};
$scope.function2= function () { //5th step
$http({
url: '/class/method2/',
method: 'POST',
params: { myValue: $scope.myvalue }
}).success(function (data) {
$scope.myValue2 = data.data; //this run as asyn after response recived
});
};
var initialize = function () {
var defer = $q.defer();
defer.promise
.then(function() {
$scope.function1(); //2nd step
})
.then(function() {
$scope.function2(); //4th step
})
defer.resolve(); //1st step
};
initialize();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.