Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I'm trying to assign array elements in a for loop with asynchronous results of a call to a ngResource action.

for ( var i = 0; i < projs.length; i++) {
    $scope.projets[i].redacteur = new Object(); // the Object where the result will be stored
    var param = new Object();
    param.email = projs[i].redacteurEmail;
    Agent.read(param, function(data) {
        $scope.projets[i].redacteur = data;
    });


}

The problem is : when the callback function is executed (when the data is received), i is out of bounds (it passed the last i++). Then the data received is assigned to a nonexistent object.

Any idea of a solution to this issue ?

share|improve this question
2  
possible duplicate of Javascript infamous Loop problem? – Fabrício Matté Nov 14 '13 at 16:10
2  
and Problem with loop – Fabrício Matté Nov 14 '13 at 16:11
2  
2  
also Why is the answer to this 10? – Fabrício Matté Nov 14 '13 at 16:12
2  
up vote 1 down vote accepted

I solved this issue by putting the call to the callback function in a closure. With my example, it looks like that :

for (var i = 0; i < projs.length; i++) {
    $scope.projets[i].redacteur = new Object(); // the Object where the result will be stored
    var param = new Object();
    param.email = projs[i].redacteurEmail;
    (function(i) {
        Agent.read(param, function(data) {
            $scope.projets[i].redacteur = data;
        });
    })(i);
}
share|improve this answer
    
Trop fort !! You saved my skin here ! I now need to read about javascript closures. – Stephane Oct 8 '14 at 13:11

I had a similar issue, and I solved it by using Promises. The basic idea is that I send the index of the array as a parameter to my asynchronous request callback, and then I can handle it when the response arrives. Hope that helps.

share|improve this answer

If I understand your issue correctly, I believe this may work.

myData = Agent.read(param, function() {
    $scope.projets[i].redacteur = myData;
});

This is the approach I have used. I'm still new to Angular, but my understanding is that myData becomes a deferred promise. As a deferred promise it must be resolved prior to use. Please, someone who has more experience Angular and deferred promises chime in.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.