Modify same object classes inside after/before save

I’ve an object and this object have a field called order, and when I save or edit it, I need to change the order of other objects, but if I call the save method inside afterSave/beforeSave it’ll create an infinite loop through it…
I was thinking to instead the default route to classes, make a function to deal with it, but I think this is a bit wrong…
How do I deal appropriately with it?

Can you share more info and what you have tried so far?

sure

Parse.Cloud.afterSave("Place", async request => {
  const requestObject = {
    railsFId: request.object.get("railsFId"),
    order: request.object.get("order")
  };
  const allPlaces = await new Parse.Query("Place")
    .equalTo("railsFId", requestObject.railsFId)
    .find();
  if (requestObject.order) {
    for (var i = 0; i < allPlaces.length; i++) {
      if (
        allPlaces[i].get("order") >= requestObject.order &&
        request.id !== allPlaces[i].id
      ) {
        allPlaces[i].set("order", allPlaces[i].get("order") + 1);
        await allPlaces[i].save(null, { useMasterKey: true });
      }
    }
  } else {
    request.object.set("order", allPlaces.length);
    await request.object.save(null, { useMasterKey: true });
  }
});

Take a look in this link

You can use request context to pass some information to be checked later and avoid the infinite loop.