0

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 ?

5

3 Answers 3

2

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Trop fort !! You saved my skin here ! I now need to read about javascript closures.
Thank you so much. I didn't understand why I had the same behavior. Using a function solved the problem.
0

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.

Comments

0

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.

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.