2016-04-14 49 views
0

我的javascript控制器中有以下代碼。這些函數在獨立於視圖和異步調用時起作用。不過,我想從第一函數的返回值在調用用於第二功能Angular Promise不能同步運行

$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返回,所以我唯一能想到的就是函數2被調用得太早了。任何指針? :-)

+1

承諾永遠不會同步。 [Promises are no magic](http://stackoverflow.com/a/22562045/1048572)。你需要從''then''回調函數''返回',並從你的函數'functionN'範圍內返回它們,否則他們不會知道你想等待任何事情。 – Bergi

+0

如果你希望function2在function1之後運行,它應該在函數1成功或其他地方調用,在檢查函數1返回期望的數據之後。 –

回答

1

initialize中的承諾同步運行。而$http請求不。這導致致電$scope.function2而無需等待$scope.function1中的承諾來解決。

應該

$scope.function1= function() { 
    return $http... 
}; 

$scope.function2= function() { 
    return $http... 
}; 

在這種情況下推遲承諾is antipatterninitialize應該是這麼簡潔:

var initialize = function() { 
    return $scope.function1().then(function() { 
      return $scope.function2(); 
    }) 
    }; 
-1
$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();