1

So, using parse.com, I'm doing some nested queries... basically, getting an object and then retrieving its relations and doing some operations.

            pageQuery.find({
            success: function (results) {
                var pages = [];

                for (var result = 0; result < results.length; result++) {
                    var resArrayLength = pages.push(results[result].toJSON());
                    var indexOfLastPush = resArrayLength - 1;
                    console.log("resArrayLength = " + resArrayLength);
                    pages[indexOfLastPush].scrapeRules = new Array();
                    console.log("index of last push set to " + indexOfLastPush);
                    var relation = results[result].relation("RulesForPage");
                    //get the related scrape rules
                    relation.query().find({                            
                        success: function (rules) {
                            console.log("Found  " + rules.length + " rules");
                            for (var i = 0; i < rules.length; i++) {
                                console.log("rule index = " + i);
                                console.log("Found rule " + rules[i].id);
                                pages[indexOfLastPush].AllRules = new Array();

                                pages[indexOfLastPush].scrapeRules.push(rules[i].id);
                                console.log("pushed rule " + rules[i].get("name") + " to page at index " + indexOfLastPush);
                            }
                        }

                    });
                }

The problem I am seeing is that I am trying to indexOfLastPush to track an array index I need, but that value has changed by the time the call back has happened.

How can I pass it to the "success" callback so I have the index I need?

UPDATE: Thanks to @cggaurav for the excellent tip. Why does it seem like the answer to every JavaScript problem is to wrap your code in an anonymous function?

1 Answer 1

2

You have to have what is called a closure or an anonymous function for every relation.query() you make. See "More on lexical scoping" | http://mark-story.com/posts/view/picking-up-javascript-closures-and-lexical-scoping

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

2 Comments

Thanks for the reply... having read the article, I'm having trouble imagining how to implement that solution. Could I trouble you for some (pseudo) code to point me in the general direction?
(function(index) { //Do your relation.query() with 'index' here })(indexOfLastPush);

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.