I'm confused as to what the purpose of the return keyword is in afterSave handlers. As far as I know it does not return the result to the client , if so then where is it returning the result to? Pic from Cloud Code documentation give below for reference.
In the code example above, which I think is from the docs, the return ensures that any error from post.save()
will get 'caught' by the catch
.
In an afterSave
hook, no error will ever be returned to the client. The object that will be returned is unaffected by anything that happens in the afterSave
.
What is influenced by the return in the afterSave
is when the connection to the client will be closed.
If you return a promise, the connection will not be closed until the promise resolves. In the case of the code you cite, the promise is not returned so the connection will be closed immediately because the afterSave
function will return before the post.save() promise is resolved.
In order for the return
that you highlighted to have any impact to the client, you'd also have to return the query like so:
Parse.Cloud.afterSave('Comment', (request) => {
const query = new Parse.Query('Post');
return query.get(....)
In which case, the client would wait for the post's comment count to be incremented and saved before the connection is closed.
Read on to understand why this matters and other fine points about afterSave
and how 'returning' works!
Here are some considerations:
afterSave
function is not async
. This would be appropriate if you wanted to update an external system or send an email as a result of the save. Here's an example of how to disconnect...const afterSave = function afterSave(request) {
const { object } = request;
got.post('htttps://my.microservice/complete', { object })
.then(() => console.log('done posting to microservice'))
.catch(console.error);
};
If there is an error posting to the 'microservice', the client will never know, but it will be logged to your console.
afterSave
is a case where you need to make sure that a related operation completes before the client gets the saved object back. For example, imagine that your need to add a new user to a role and that that operation needs to be completed before returning the user to the client or an error will occur due to lack of permissions. In this case, you need the user to be saved, which gives it an id, before you can add her to a role. So, in this case, you would add the user to the role in the afterSave
which is an async operation and return the resulting promise so that the state of the user's permission will be set and known when the client gets the returned user object.Hope this helps!