我无法弄清楚我如何将Promise范例应用于我的代码。 我的代码并没有弄清楚它应该如何。最后2个查询未执行... 第一个(mainQuery)仅限于< = 5个项目,所以它应该足够快。 管道应该是: query1.find() - >对于找到的所有元素 - > gt;如果元素是类型1 - > query2.count() - > if count == 0->保存新对象
你能帮我解决一下吗? 先感谢您, 米歇尔
mainQuery.find().then(
function(items){
for (var i = 0; i < items.length; i++) {
if(items[i].get("type") == 1){
var query = new Parse.Query("Invites");
//query.equalTo("userId","aaaaaaaa")
query.count().then(function(count){
console.log("why i don't see it in logs...??");
if (count == 0){
var invite = new Parse.Object("Invites");
//invite.set("userId", "aaaaaaa");
invite.save();
}
}, function(error){
response.error("Msgs lookup failed");
});
}
}
response.success(items);
},
function(error) {response.error("Msgs lookup failed");
});
答案 0 :(得分:0)
我认为问题在于您在执行其他查询之前调用了response.success。 代码看起来应该更像:
mainQuery.find().then(
function(items){
var promises = [];
for (var i = 0; i < items.length; i++) {
if(items[i].get("type") == 1){
var query = new Parse.Query("Invites");
//query.equalTo("userId","aaaaaaaa")
// first promise which needs to be resolved
var countPromise = query.count().then(function(count){
console.log("why i don't see it in logs...??");
if (count == 0){
var invite = new Parse.Object("Invites");
//invite.set("userId", "aaaaaaa");
// instead of an resolved object, we return another promise which will be resolved
// before entering the success part below
return invite.save();
} else {
// if there is nothing to do, we return an promise which will be resolved with a dummy value
return Promise.as('nothing to do');
}
});
promises.push(countPromise);
}
}
return Parse.Promise.when(promises).then(function (results) {
// we only get in here when all promises aboth has been resolved
response.success(items);
});
},
function(error) {
// if any of the requests fail, this method will be called
response.error("Msgs lookup failed");
});
您可以在官方文档中找到有关如何链接承诺的其他信息:https://parse.com/docs/js/guide#promises-promises-in-parallel