2

I'm trying to save a collection of objects from a Cloud Code function.

After 30-40 objects I get a time out error. My code looks like this:

Parse.Cloud.define("saveInBackground", function (request, response) {
    console.log("saveInBackground begin");

    var objectsToSave = [];

    for (var i = request.params.collectionToSave.length - 1; i >= 0; i--) {
        objectsToSave.push(new LikedObject(request.params.collectionToSave[i])); 
    };

    Parse.Object.saveAll(objectsToSave, {
        success: function(list) {
            // All the objects were saved.
            if (response) {
                response.success(list);
            };

            console.log("saveInBackground success");
        },
        error: function(model, error) {
            // An error occurred while saving one of the objects.
            if (response) {
                response.error(error);
            };

            console.log("saveInBackground error: " + error.message);
        }
    });

    console.log("saveInBackground end");
});

Can I do something else in order to save a bunch of objects?

4

1 回答 1

4

根据对象的大小,您可以尝试以 20-30 个为一组进行保存。这是必需的,因为saveAll()它试图将您提供的所有对象上传到服务器。这是您如何执行此操作的示例代码:

var result = true;
for (var i = request.params.collectionToSave.length - 1; i >= 0; i--) {
    objectsToSave.push(new LikedObject(request.params.collectionToSave[i])); 
    if (i % 10 == 0) {
        result = saveObjects(objectsToSave);
        objectsToSave.length = 0;
    }
};
if (result == true) {
    console.log("saveInBackground success");
}


function saveObjects(objects) {

    Parse.Object.saveAll(...);
    ...
}
于 2012-12-29T17:17:57.147 回答