javascript - AngularJS : How to work with Angular Promises -


this question has answer here:

i have function makes rest service call wan use populate array data returned. angular returns promise, , not know how work data in promise populate array.

my function:

    $scope.save= function(){      var duplicatenames= [];     for(var i=0; < 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, want keep track of in array. how "pause" execution array "duplicatenames" have "aname" added it?

you can't pause execution, whole point of promise executes asynchronously. code continues execute while http request being processed. once http request has returned result, success function called. in example provided console.log statement executes before responsepromise.success function. if move log statement success function, see expected results.

in example, duplicatnames array not model of current $scope, it's of limited value, you've discovered - value of array when function exits not value interested in. if, however, make array model attaching controller's $scope, can use 2-way binding or $watch statement updated value.

basically need start thinking asynchronously, , understand processes on other end of http request may take time need account it. there tons of resources on learning angular promises here 4:


Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -