Say you have a "define" Parse.com cloud code function...
Parse.Cloud.define("exampleDefineFunction", function(request, response)
{
...
response.success("ok")
...
response.error("doh")
});
I want to make another cloud code function,
which calls that define function a number of times in series,
with one waiting for the next, much as in a serial promise chain
Can this be done?
I think this should do the trick!
In this scenario we want to use Parse.Promise.when()
Returns a new promise that is fulfilled when all of the input promises are resolved. If any promise in the list fails, then the returned promise will fail with the last error. If they all succeed, then the returned promise will succeed, with the results being the results of all the input promises
I've tried to make it fairly self-documenting but let me know if you have any questions. Hope this helps!
// The promise chain for bulk image collection
Parse.Cloud.define("fetchBulkImages", function(request, response) {
// Array of URLs
var urls = request.object.get("urls");
// Array of promises for each call to fetchImage
var promises = [];
// Populate the promises array for each of the URLs
_.each(urls, function(url) {
promises.push(Parse.Cloud.run("fetchImage", {"url":url}));
})
// Fulfilled when all of the fetchImage promises are resolved
Parse.Promise.when(promises).then(function() {
// arguments is a built-in javascript variable
// will be an array of fulfilled promises
response.success(arguments);
},
function (error) {
response.error("Error: " + error.code + " " + error.message);
});
});
// Your scraping function to load each individual image
Parse.Cloud.define("fetchImage", function(request, response) {
...
response.success("image successfully loaded")
...
response.error("Error: " + error.code + " " + error.message);
});
Have you considered using a beforeSave cloud hook to do the pre-save checking?
In terms of executing them one at a time, you could look into using a serial promise chain to queue up whatever you need. Each promise will have it's own pair of callbacks for handling if the promise was resolved or rejected.
Also, the current setup seems like it will rapidly cause you to hit your API request limit. Have you thought about performing a single query with the array of URLs to check as a constraint. With that one query, you will know which of the items in the array already exist.
来源:https://stackoverflow.com/questions/32768731/in-cloud-code-call-a-parse-cloud-run-function-more-than-once-in-series