Angular Promise没有同步运行

时间:2016-04-14 10:57:48

标签: javascript angularjs asynchronous promise synchronous

我的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为null。数据已从函数1返回,因此我唯一能想到的是函数2被过早调用。有什么指针吗? : - )

2 个答案:

答案 0 :(得分: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 :(得分:-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();
相关问题