1

I have a LIST of Id's and I want all of them to contact my API.

The way I did it is like this:

 var someFunct = function() {
      for (var i = 0; i < Apples.length; i++) {
       var Apple = Apples[i];
        $http.get("APIUrl" + Apple.Id).
        success(function (response) {
            for (var i = 0; i < response.Appleseeds.length; i++) {

                if(Apple.Appleseeds.Id == response.Appleseeds.Id)
                {
                    Apple.Size = response.Appleseeds.Size;
                }
            }               
        })

    }

So the problem is that Apple[2] has changed value, where Apple[0] and Apple[1] stay untouched. response.Appleseeds have their own list of Id's. So I need to change the Size of ALL THE APPLES not just Apple[2].

2 Answers 2

5

You're close, use a closure instead:

var someFunct = function () {
    for (var i = 0; i < Apples.length; i++) {
        (function (Apple) {
            $http.get("APIUrl" + Apple.Id)
            .success(function (response) {
                for (var i = 0; i < response.Appleseeds.length; i++) {

                    if (Apple.Appleseeds.Id == response.Appleseeds.Id) {
                        Apple.Size = response.Appleseeds.Size;
                    }
                }
            });
        })(Apples[i]);
    }
};

Because http doesn't happen instantly, by the time the last success has happened in your code apple has been changed. By wrapping it in a closure you make it so that each call has it's own private Apple.

Sign up to request clarification or add additional context in comments.

1 Comment

Its working! thank you ! in 3 min i give you "Correct answer" :D Need to read about closure..
1
var deferred = $q.defer();
var someFunct = function() {
  for (var i = 0; i < Apples.length; i++) {
    $http.get("APIUrl" + Apples[i].Id).
    success(function (response) {
         deferred.resolve(response)              
    })
    return deferred.promise;
 }
}

someFunct().then(function(d)){
    // write your code here
   } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.