In cloud code, call a Parse.Cloud.run function more than once in series

橙三吉。 提交于 2019-11-28 01:44:55
Russell

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!