0

I have a function that makes a rest service call that I wan to use to populate an array from the data returned. Angular returns a Promise, and I do not know how to work with the data in the Promise to populate an array.

My function:

    $scope.save= function(){

    var duplicateNames= [];
    for(var i=0; i < ids.length; i++){
        var id= "bns-" + i;
        var aName= document.getElementById(id).value;
        var responsePromise= $http.get("/rest/v1/names/" + aName + "/");
        responsePromise.success(function(data, status, headers, config) {
            if(data.name.length > 0)
                duplicateNames.push(data.name);
        });
    }
    console.log(duplicateNames);

The rest call returns data if "aName" exists, then I want to keep track of it in the array. How do I "pause" execution so that the array "duplicateNames" will have "aName" added to it?

John Slegers
  • 45,213
  • 22
  • 199
  • 169
bmw0128
  • 13,470
  • 24
  • 68
  • 116

1 Answers1

0

You can't pause execution, the whole point of a promise is that it executes asynchronously. That is to say your code continues to execute while the http request is being processed. Once the http request has returned a result, your success function is called. In the example you provided the console.log statement executes before the responsePromise.success function. If you move the log statement into the success function, you will see the expected results.

In your example, the duplicatNames array is not a model of the current $scope, so it's of limited value, as you've discovered - the value of the array when the function exits is not the value you are interested in. If, however, you make the array a model by attaching it to the controller's $scope, you can use 2-way binding or a $watch statement to do something with the updated value.

Basically you need to start thinking asynchronously, and understand that processes on the other end of an HTTP request may take time which you need to account for it. There are tons of resources on learning about angular promises here are 4:

Community
  • 1
  • 1
Jason
  • 15,915
  • 3
  • 48
  • 72