所以,使用 parse.com,我正在做一些嵌套查询......基本上,获取一个对象,然后检索它的关系并执行一些操作。
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);
}
}
});
}
我看到的问题是我试图 indexOfLastPush 来跟踪我需要的数组索引,但是在回调发生时该值已经改变。
如何将它传递给“成功”回调,以便获得所需的索引?
更新: 感谢@cggaurav 提供的出色提示。为什么似乎每个 JavaScript 问题的答案都是将代码包装在匿名函数中?