Correct way of retrieving values from an array (Truffle/Pudding)

mati21mati21 Member Posts: 8
edited May 2016 in web3-js
I have a public array called posts in my contract which is called social and is instantiated with help of the Truffle/Pudding framework.
On the frontend I am trying to retrieve values from the array by looping through the values in the following way:

length = 3;
posts = new Array(length);

for(var i = 0; i < length; i++ ){
social.posts.call(i).then(function(v){
posts[i] = v;
});
}
From my understanding the problem seems to be that the promise takes the anonymous function which doesn't get evaluated until the end of the loop. Hence the values of i are not passed correctly. The anonymous function gets executed only once with a value i == 3.
Is there any other easy way to retrieve values from the array or a workaround to make this work? I was trying to somehow wrap the function into a closure (IIFE) but somehow I don't know how to do this or it's not possible.
Sign In or Register to comment.