Async parse query inside BeforeSave trigger?

Hi. I wanna run some parse query inside beforeSave trigger.

If post author blocked the comment author, I wanna throw an exception but seems like doesnt work?

Parse.Cloud.beforeSave("Comment", (request) => {
  const user = request.user;
  const query = new Parse.Query("Post");
  query.include("user");
  query.get(request.object.get("post").id)
    .then(function(post) {
      const otherUser = post.get("user");

      const Block = Parse.Object.extend("Block");

      const query2 = new Parse.Query(Block);
      query2.equalTo("who", user);
      query2.equalTo("owner", otherUser);
      query2.limit(1);



      query2.find().then(function(results) {
        if(results.length>0){
          throw "1154";
        }
      });



    })
    .catch(function(error) {
      console.error("Got an error " + error.code + " : " + error.message);
    });
});

But seems like this doesnt work. Any idea?

Are you sure that the throw line is reached at all? E.g. by adding a log statement inside the if block.

You are throwing the exception from inside the callback. So it will not work as you expect. Try this:

Parse.Cloud.beforeSave("Comment", async request => {
  const user = request.user;
  const query = new Parse.Query("Post");
  query.include("user");
  const post = await query.get(request.object.get("post").id)
  const otherUser = post.get("user");

  const Block = Parse.Object.extend("Block");

  const query2 = new Parse.Query(Block);
  query2.equalTo("who", user);
  query2.equalTo("owner", otherUser);
  query2.limit(1);



  const resultsCount = await query2.count();
  if(resultsCount>0){
    throw "1154";
  }
});
1 Like

Thank you It works now. One more question and I think its more related to javascript than Parse Server.

Parse.Cloud.beforeSave(“Comment”, async request =>

What does “async” do?

I tried to use “await” in aftersave trigger. I used directly examples in this docs. There is no async in those examples But When I use await with those examples, I got an error which says some thing like this (I cant remember the exact error) “You cannot use await in non async function”

I really wonder what async do?

Also do you have any javascript tutorial recommendation for basic javascript for cloudcode?

The examples you sent also work but they use the promises directly instead of the async/await style. You can go through either ways but the async/await style is more clean. Long story short the async function operates asynchronously implicitly returning a Promise. It is required when using the await which makes the function to await for a promise to resolve. Async, await, and promises are actually concepts that belong to Javascript in general and not specifically to Parse Cloud Code. So you can refer to any javascript tutorial about these topics.

1 Like