Cloud Code function keeps looping and creating multiple objects

I have written a function to pass on each user and set a business Object. However, the function never stops and keep on creating object multiple time for the same users.

Here’s the function in question :

Parse.Cloud.define(‘setBusinessForUsers’, async function(req,res){

var userQuery = new Parse.Query('_User');
const Business = Parse.Object.extend("Business");
userQuery.doesNotExist("business");
userQuery.limit(4000);
try{
    var results = await userQuery.find();
    for(var i=0; i < results.length; i++){
        var currentUser = results[i];
        var firstName = currentUser.get("firstName");
        var lastName = currentUser.get("lastName");
        var fullName = firstName + " " + lastName;

        
        var business = new Business();

        business.set("name",fullName);
        business = await business.save();


        currentUser.set('business',business);
        
        var savedUser = await currentUser.save(null,{useMasterKey: true});
    }
   
    console.log("Done");
    return "Done";
}catch(e){
    throw new Error(e);
}

});

Can’t see anything obviously wrong with it.

How are you calling it? It may be that it’s taking a long time and the client is trying the call again because it thinks the function hasn’t returned / timed out.

1 Like

Yea this could be a request timeout since I reduced the limit to 100 and it worked.
I’m calling it from my android device with no call backs

HashMap<String,Object> params = new HashMap<>();
ParseCloud.callFunctionInBackground(“setBusinessForUsers”,params);

Any idea how to get it working with one call ( Instead of calling it multiple times)

If you don’t care about the result anyway you could simply return immediately after spawning the real work asynchronously. Something like

Parse.Cloud.define('setBusinessForUsers', async (req) => {
  setBusinessForUsers(req) // no await here!
  return 'Done'
})

async function setBusinessForUsers(req) {
  // your business code goes here
}

Now in the app you will immediately receive the success message, however you will not be able to find out if the business logic succeeded or failed. I wouldn’t suggest this approach in general but in your case (ignoring the result anyway) it’s okay-ish.