0

I am attempting to write an Angular page to communicate with my Nodejs server, but I have ran into a snag.

I need to use multiple Ajax requests that rely on the data from previous ajax requests to work.

So Ajax request #1 provides data that is used by all other Ajax requests, and Ajax request #2 uses data from ajax request #1 to get the data that Ajax request #3 needs.

Since Angular is asynchronous, how can I make my script wait for the data from the first one before making the next ajax call.

id = ajax()

Wait for data

token = ajax(id)

wait for data

gametoken = ajax(id, token)

wait for data

4

1 回答 1

2

Chandermani 是正确的,只要记住确保在您需要的范围内使您需要的变量可用。

var id,token,gametoken;
$http.get('http://host.com/first')
   .then(function(result){
       id=result;
       return $http.get('http://host.com/second/'+id);
    }
    .then(function(result){
        token = result
        return $http.get('http://host.com/third'+id+'/'+token);
    }
    .then(function(result){
        gametoken = result;
        //Do other code here that requires id,token and gametoken
    }

编辑:您不必链接承诺。如果你想在以后打一个电话,并且你想确保承诺已经解决,你可以使用 $q.all();

var id,token,gametoken;
var p1 = $http.get('http://host.com/first')
   .then(function(result){
       id=result;
    }

// Later on to make your new second call
 $q.all([p1]).then(function(){
      //Make second call knowing that the first has finished.
 }

$q.all() 接受一个数组,因此您可以根据需要输入多个 Promise,它会等到它们全部解决。

于 2013-11-04T05:38:43.390 回答