Roll20 uses cookies to improve your experience on our site. Cookies enable you to enjoy certain features, social sharing functionality, and tailor message and display ads to your interests on our site and others. They also help us understand how our site is being used. By continuing to use our site, you consent to our use of cookies. Update your cookie preferences .
×
Create a free account
This post has been closed. You can still view previous posts, but you can't post any new replies.

Using getAttrs() inside a for loop isn't working

1457976035
James
Sheet Author
Hi, I'm still working out how to write sheetworkers for a character sheet that I'm hoping will go to the community github.  I've had trouble using getAttrs inside a for loop.  I'm trying to work through each entry in a repeating fieldset, grab the value of the "attr_college" field, and concatenate them all together, so that I can test if they are all empty or not. When I run this, getAttrs seems to run AFTER the for loop, so only the last use of v[...] has an entry and the previous ones are all returned as undefined. Is this the intended behaviour?  If so, how can I work with the values of a field in a repeating fieldset (e.g. checking their blank, getting a total)? The code that is giving me trouble is: on("change:repeating_college remove:repeating_college", function() {     getSectionIDs("repeating_college", function(idArray) {         if(idArray.length == 0) { // Do one thing         }         else {             console.log(idArray);             var concat = "";             for (var i=0; i < idArray.length; i++) {                 var idname = idArray[i];                 console.log("attrname: " + "repeating_college_" + idname + "_college");                 getAttrs(["repeating_college_" + idname + "_college"], function(v) {                     console.log(v["repeating_college_" + idname + "_college"]);                     concat += v["repeating_college_" + idname + "_college"];                     console.log("concat: " + concat);                 });             }         }     }); }); Many thanks!
1457986152
Phil B.
Forum Champion
Sheet Author
The getAttrs function runs asynchronously, so the loop will start [idArray.length] number of getAttrs function "threads" that will all run side-by-side and complete possibly out of order. 
1457988630
James
Sheet Author
Hey Phil - thanks for the confirmation that it is running as intended (i.e. asynchronously). It took me a while, but I think I understand that the getAttrs "threads" can run AFTER the for loop has closed and thus, the value of idname has already been updated to the final value, and that is what is used in each of the "threads" - i.e. the different values of idname aren't passed through to the respective threads. I don't know if that makes sense to you, it just about makes sense to me! Thanks again.