Ad

What Happens When A Parse Cloud Function Returns A Promise?

- 1 answer

This is a very simple question, but I can't find an answer to it in the Parse docs, nor in StackOverflow.

If I have a Parse Cloud function, e.g.:

Parse.Cloud.define("someFunction", function (req, res) {
  return new Parse.Promise(function (resolve, reject) {
    // Do something then resolve or reject
  }
}

and I call it from my mobile app:

Parse.Cloud.run("someFunction", {})

What happens to the Promise returned by Parse.Cloud.run?

I tested this, and it appears never to resolve nor reject. I know that the concept of a promise created on one host resolving remotely to another host is probably not possible, but I have no idea how Parse works under the hood. (And it would be super cool if it did work this way!)

Thanks.

Ad

Answer

It happens almost as you wish. Cloud functions get passed a FunctionResponse object which implements success() and error(), so...

Parse.Cloud.define("someFunction", function (request, response) {
    var anyPromise = // anything that creates a promise
    // no reason to return here, the caller is opaque
    anyPromise.then(function(result) {
        response.success("this will be what Cloud.run resolves to");
    }, function(error) {
        response.error("this will be passed to the reject function of Cloud.run");
    });
});

The other nice thing this does is hide the network serialization for us, so...

response.success(anyObject);

will serialize any object, return it, and rebuild it as a parameter to the resolution...

Parse.Cloud.run("someFunction", {}).then(function(result) {
    // result == anyObject
});
Ad
source: stackoverflow.com
Ad