您的函數在查詢完成前運行response.success(),從而取消它。試試...
Parse.Cloud.beforeSave("UserRewards", function(request, response) {
var relation = request.object.relation("user");
relation.query().find({
success: function(list) {
console.log("looked up relation");
if (list.length > 0) {
var pUser = list[0];
request.object.set("pUser", pUser);
console.log("updated pUser");
}
response.success();
},
error: function(error) {
console.error("unable to lookup relation");
response.error(error);
}
});
});
或者,看看容易在與承諾...
Parse.Cloud.beforeSave("UserRewards", function(request, response) {
var relation = request.object.relation("user");
relation.query().find().then(function(list) {
console.log("looked up relation");
if (list.length > 0) {
var pUser = list[0];
request.object.set("pUser", pUser);
console.log("updated pUser");
}
response.success();
}, function(error) {
console.error("unable to lookup relation");
response.error(error);
});
});
編輯我想我明白了後續問題的要求,以同步與關係屬性的指針屬性,假設在保存之前只設置了其中的一個。這可以通過檢測關係爲空來完成。如果是的話,再做一個異步步驟來獲取指針...
Parse.Cloud.beforeSave("UserRewards", function(request, response) {
var relation = request.object.relation("user");
relation.query().find().then(function(list) {
console.log("looked up relation");
if (list.length > 0) {
var pUser = list[0];
request.object.set("pUser", pUser);
console.log("updated pUser");
return Parse.Promise.as(); // we're done, this will pass nothing to the next step
} else { // the relation is empty, so the user pointer must be set
var pointer = request.object.get("pUser");
return pointer.fetch(); // this will pass the pUser to the next step
}
}).then(function(pUser) {
if (pUser) {
// must have found an empty relation in the last step. add the user pointer to it
request.object.relation.add(pUser);
}
response.success();
}, function(error) {
console.error("unable to lookup relation");
response.error(error);
});
});
(注意代碼未經測試)。
嗨丹,謝謝你的回答。那就是訣竅。我有一個後續問題。如果我想檢查關係是否已設置,然後將指針設置爲未設置,該怎麼辦?並設置關係,如果沒有設置,但指針設置?隨意修改上面的答案。承諾是好的。 – amit 2015-01-27 21:48:20
@amit - 給了我最好的拍攝。 – danh 2015-01-27 22:31:54
這樣做的工作,如果關係是零? – amit 2015-01-27 23:46:52