post请求总是在angularjs函数的最后一个执行(不是按顺序执行)

post request always executed at last angularjs function (not executing sequentially)

本文关键字:执行 最后一个 顺序 请求 angularjs 函数 post      更新时间:2023-09-26

我面临一个问题。我有angularjs函数,它反过来调用另一个有post请求的angular函数。当第一个函数结束时,这个post请求总是在最后激发。。它不是按顺序发射的。

   pseudo code
     $scope.fun1= function()
         {
            $scope.fun2();

            console.log("after call to  fun2"); // execute before fun2
         }
   $scope.fun2=function()
        {
          $http.post(valid request);///this always executed at last..means at end of  function 1...no matter  at what position i call it
       }

请有人给我解释一下这种行为。。对此有任何解决方法。。。我想按顺序执行所有http请求。提前感谢!

您可以使用promise。promise将为您提供一个变量,您可以在该变量上调用register,根据将来发生的某个事件调用一段代码——在本例中,$http.post((返回。您可以在这里阅读更多关于promise的信息,并在下面查看您修改后的伪代码。

//       pseudo code
     $scope.fun1= function()
         {
            $scope.fun2().then(function(data) {
                 console.log("after call to  fun2"); // execute before fun2
             });

         }
   $scope.fun2=function() {
           var deferred = $q.defer();
            $http({
                url: "whatever/something",
                method: "POST",
                params: {// if you need params}
            }).success(function (data) {
                deferred.resolve(data);
            }).error(function () {
                deferred.resolve(null);
            });
            return deferred.promise;
       }

您想要的是一个同步调用。虽然这在XmlHttpRequest对象中是可能的,但angular$http目前不支持这一点,并且在等待服务器响应时冻结网页被认为是糟糕的编程实践。如果您希望控制台日志在发布后执行,您可以返回对.post()的调用结果,并在调用完成后使用.success()方法执行某些操作(PLNKR(:

var app = angular.module("MyApp", []);
var ctrl = app.controller("MyCtrl", function($scope, $http) {
  $scope.fun1 = function() {
    $scope.fun2().success(function(data) {
      console.log('after call to fun2');
    });
  };
  $scope.fun2 = function() {
    var result = $http.get('data.json').success(function(data) {
      console.log('fun2 got', JSON.stringify(data));
    });
    return result; // still has .success() and .error() functions on it
  };
})