Cloud Code return asynchronously

Hello guys,
I’m trying to return an object from cloud function. I first tried to return inside the .then() method but it returned null probably because it didn’t wait. So I had to use await. However what about other requests, would the await slow it down for others? Also isn’t there a listener to return when the object has loaded asynchronously?
( Best practices to return an object asynchronously from cloud functions is what I need basically)

Also how would you handle errors when using await ? check if the result is null ?

Considering that you are running Parse Server 3.x, it would be something like this:

Parse.Cloud.define("myFunction", async request => {
  const myObject = new Parse.Object("MyClass");
  myObject.set('someField', 'someValue');
  try {
    return await myObject.save();
  } catch (e) {
    console.error(e);
    throw new Error('My custom error message');
  }
});
2 Likes

Got it that’s for handling error for the await part. But if I use await it doesn’t become asynchronous anymore right ? Will it have an effect on other users who are requesting the cloud functions ?

There is no effect for other cloud function requests. Two of these functions I wrote can run at the same time. While one “await myObject.save();” is running and waiting response from the database, other function can start running at same time.

But within a cloud function, yes. A second operation will wait for the first one. For example:

await myObject1.save();
await myObject2.save();

The second save will only start when the first one is completed. If you want to run both in parallel, you can do something like this:

const promise1 = myObject1.save();
const promise2 = myObject2.save();
await Promise.all([promise1, promise2]);
1 Like

Awesome reply David! Thank you for your answer :slight_smile: