我为Parse Framework编写了一个异步云后台作业,根据“@”符号之前的电子邮件为每个用户生成一个显示用户名。不幸的是,当我运行这份工作时,我收到的错误是“计算操作太多”。有没有办法让查询和保存串联运行而不是并行运行?我在文档中看到了promises的可能性,但我对如何使用嵌套查询感到困惑。
Parse.Cloud.job("generateUsernameForEveryUser", function(request, status) {
// Set up to modify user data
Parse.Cloud.useMasterKey();
var counter = 0;
// Query for all users
var query = new Parse.Query(Parse.User);
query.each(function(user) {
createUsernameForUser(user, 0, {
success: function(username) {
if(username == null) {
status.error();
} else {
user.set("displayUsername", username);
user.set("displayUsernameUppercase", username.toUpperCase());
user.save();
}
},
error: function(error) {
status.error("Error: " + error.message);
}
});
}).then(function() {
// Set the job's success status
status.success("Username generation completed successfully.");
}, function(error) {
// Set the job's error status
status.error("Uh oh, something went wrong.");
});
});
function createUsernameForUser(user, count, callback) {
var generatedUsername = user.getEmail().substring(0, user.getEmail().indexOf("@"));
if(count > 0) {
//Quotes added to ensure no math is done between generatedUsername and count
generatedUsername = "" + generatedUsername + "" + count;
}
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo("displayUsernameUppercase", generatedUsername.toUpperCase());
userQuery.count({
success: function(userCount) {
if(userCount > 0) {
createUsernameForUser(user, count + 1, {
success : function(responseUsername) {
callback.success(responseUsername);
},
error: function(error) {
callback.error(error.message);
}
});
}
else {
callback.success(generatedUsername);
}
},
error: function(error) {
console.log("Error trying to count users: " + error.message);
callback.error("Error trying to count users: " + error.message);
}
});//End of userQuery call
}
答案 0 :(得分:0)
这是一个非常晚的答案,但对于经历这个的人来说会有所帮助。
返回 too many count operations
错误,因为只有当我们为该类提供100或更少行的数据时,query.each才会起作用。
我们可以达到以下相同的要求:
var users = new Array();
.... push all the created user objects to users ....
Parse.Object.saveAll(users); //save the list -
希望这能解决。