Javascript AngularJS+$q、 在多个ajax调用完成后执行某些操作

Javascript AngularJS+$q、 在多个ajax调用完成后执行某些操作,javascript,ajax,angularjs,angular-promise,Javascript,Ajax,Angularjs,Angular Promise,我需要在页面加载中加载一些数据,然后执行一个任务。为了获得我想要的数据,我执行了多个不同的ajax调用。但是为了执行任务,我需要确保所有ajax调用都已完成。以下是我迄今为止所做的工作: $q.when( $http.get('url1').success(function (data) { $scope.data1 = data; console.log("ajax1 finished"); }),

我需要在页面加载中加载一些数据,然后执行一个任务。为了获得我想要的数据,我执行了多个不同的ajax调用。但是为了执行任务,我需要确保所有ajax调用都已完成。以下是我迄今为止所做的工作:

$q.when(
        $http.get('url1').success(function (data) {
            $scope.data1 = data;
            console.log("ajax1 finished");
        }),
        $http.get('url2').success(function (data) {
            $scope.data2 = data;
            console.log("ajax2 finished");
        }),
        $http.get('url3').success(function (data) {
            $scope.data3 = data;
            console.log("ajax3 finished");
        }),
        $http.get('url4').success(function (data) {
            $scope.data4 = data;
            console.log("ajax4 finished");
        })
    ).then(
        console.log("All ajax calls have finished!"),
        executeTask()
    );
我的问题是块
中的代码然后(…)不会执行代码>。我的控制台里有这样的东西:

ajax2 finished
ajax1 finished
All ajax calls have finished!
ajax3 finished
ajax4 finished
我一定是做错了什么。我怎样才能让它按我想要的方式工作


编辑:我尝试了以下答案中提到的方法,但我仍然面临同样的问题

$q.all([
    $http.get('url1').then(function (data) {
        $scope.data1 = data;
        console.log("");
    }),
    $http.get('url2').success(function (data) {
        $scope.data2 = then;
        console.log("ajax2 finished");
    }),
    $http.get('url3').then(function (data) {
        $scope.data3 = data;
        console.log("ajax3 finished");
    }),
    $http.get('url4').then(function (data) {
        $scope.data4 = data;
        console.log("ajax4 finished");
    })
]).then(
    console.log(""),
    executeTask()
);

您有两种解决方案:

  • 您想使用
    $q.all()
    等待多个承诺的解析。例如:

  • 在呈现屏幕之前,使用routeProvider的
    解析
    机制预加载promise:


我使用
$q.all()


检查我的编辑。我尝试使用$q.all,但它仍然不能按我想要的方式工作。我相信
$q.all
应该接受promises@maurycy我也试过了,但没用。你在编辑的帖子中仍然有一个成功的电话。谢谢。错误是我在做
.then(myTask())
而不是
.then(function(){myTask()})
。它就在我眼前,但我错过了。还记得
promise
for
$http
返回的响应对象包含很少的值,其中一个是您可能不想使用的
数据
  $q.all([
    $http.jsonp('http://ip.jsontest.com/?callback=JSON_CALLBACK').then(function(response) {
      $scope.ip.one = response.data
      console.log('one')
    }),
    $http.jsonp('http://ip.jsontest.com/?callback=JSON_CALLBACK').then(function(response) {
      $scope.ip.two = response.data
      console.log('two')
    }),
    $http.jsonp('http://ip.jsontest.com/?callback=JSON_CALLBACK').then(function(response) {
      $scope.ip.three = response.data
      console.log('three')
    }),
    $http.jsonp('http://ip.jsontest.com/?callback=JSON_CALLBACK').then(function(response) {
      $scope.ip.four = response.data
      console.log('four')
    }),
  ]).then(function() {
    console.log('all')
  })