I wrote an asynchronous background cloud job for the Parse Framework that generates a display username for each user based on their email, before the "@" character. Unfortunately, I get the error "too many counting operations" when completing a job. Is there a way for queries and saves to be executed sequentially, rather than in parallel? I saw this in the documentation with promises, but I'm confused about how to make it work with nested queries.
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 success status status.success("Username generation completed successfully."); }, function(error) { // Set the job 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 }
source share