Angular Promise未同步运行

Angular Promise not running synchronously

本文关键字:运行 同步 Promise Angular      更新时间:2023-09-26

我的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被调用得太早了。有指针吗?:-)

initialize中的promise同步运行。而$http请求没有。这导致在不等待$scope.function1中的promise解析的情况下调用$scope.function2

应该是

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

在这种情况下,延迟承诺是反模式的,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();