我写了一些Cloud Code,它在每个用户保存后执行。在内部,我想将用户添加到两个角色,Alpha和Free,但此代码仅成功地将新用户添加到Alpha角色; Free角色在users表中没有数据。 Parse有没有办法为用户分配多个角色?
这是我的Cloud Code。
Parse.Cloud.afterSave(Parse.User, function(request, response) {
Parse.Cloud.useMasterKey(); // grant administrative access to write to roles
var user = request.object;
query = new Parse.Query(Parse.Role);
query.equalTo("name", "Alpha");
query.first ( {
success: function(object) {
object.relation("users").add(user);
object.save();
response.success("The user has been authorized.");
},
error: function(error) {
response.error("User authorization failed!");
}
});
query = new Parse.Query(Parse.Role);
query.equalTo("name", "Free");
query.first ( {
success: function(object) {
object.relation("users").add(user);
object.save();
response.success("The user has been authorized.");
},
error: function(error) {
response.error("User authorization failed!");
}
});
});
答案 0 :(得分:1)
问题在于排序。在调用response.success()之前,我们需要完成所有查询和保存。就像现在一样,代码中的操作时间不是确定性的。使用解析sdk ...
返回的promise来清理它Parse.Cloud.afterSave(Parse.User, function(request, response) {
Parse.Cloud.useMasterKey(); // grant administrative access to write to roles
var user = request.object;
query = new Parse.Query(Parse.Role);
query.equalTo("name", "Alpha");
query.first().then(function(object) {
object.relation("users").add(user);
return object.save();
}).then(function() {
query = new Parse.Query(Parse.Role);
query.equalTo("name", "Free");
return query.first();
}).then(function(object) {
object.relation("users").add(user);
return object.save();
}).then(function() {
response.success("The user has been authorized.");
}, function(error) {
response.error("error: " + error.message);
});
});