我遇到问题listsQuery
在所有内容都被发送到浏览器时没有执行。我知道我需要一个承诺或其他东西,但我的尝试到目前为止都没有成功。救命啊!
function processNavigation(navigation) {
var nav = [];
_.each(navigation, function(navItems) {
var navProperties = {
name: navItems.get("Name"),
longName: navItems.get("LongName"),
icon: navItems.get("Icon"),
url: navItems.get("Url"),
module: navItems.get("Module"),
runScript: navItems.get("RunScript"),
sortOrder: navItems.get("SortOrder")
};
switch (navItems.get("Module")) {
case "lists":
var listsQuery = new Parse.Query("ListItems"); // This should return back! But it's async? Needs promise?
listsQuery.ascending("SortOrder");
listsQuery.find().then(
function(results) {
var list = [];
_.each(results, function(listItems) {
var listProperties = {
name: listItems.get("Name"),
subName: listItems.get("Subname"),
sortOrder: listItems.get("SortOrder")
};
});
list.push(listProperties);
navProperties["source"] = list;
},
function() {
res.send('error');
}
);
break;
default:
navProperties["source"] = null;
break;
}
nav.push(navProperties);
});
res.send(nav);
}
答案 0 :(得分:0)
这应该会给你一些事情,我不确定它是否会奏效,但它应该向你展示这个概念。
您需要做的是创建一个promises数组,因为它看起来像是对数组中的每个项执行查询,并且因为查询需要一些时间才能在查询完成之前发送响应。然后,您可以评估承诺数组,并仅在解决后发回您的回复。
我建议你将逻辑分成几个函数,因为它有点难以理解。
function processNavigation(navigation) {
var nav = [];
var promises = []
_.each(navigation, function(navItems) {
var navProperties = {
name: navItems.get("Name"),
longName: navItems.get("LongName"),
icon: navItems.get("Icon"),
url: navItems.get("Url"),
module: navItems.get("Module"),
runScript: navItems.get("RunScript"),
sortOrder: navItems.get("SortOrder")
};
switch (navItems.get("Module")) {
case "lists":
promises.push((function(navProperties){
var listsQuery = new Parse.Query("ListItems"); // This should return back! But it's async? Needs promise?
listsQuery.ascending("SortOrder");
listsQuery.find().then(
function(results) {
var list = [];
_.each(results, function(listItems) {
var listProperties = {
name: listItems.get("Name"),
subName: listItems.get("Subname"),
sortOrder: listItems.get("SortOrder")
};
});
list.push(listProperties);
navProperties["source"] = list;
promise.resolve();
},
function() {
promise.reject();
res.send('error');
}
);
})(navProperties))
break;
default:
navProperties["source"] = null;
break;
}
nav.push(navProperties);
});
Parse.Promise.when(promises).then(function(){
res.send(nav);
})
}