Skip to content

Instantly share code, notes, and snippets.

@spacenick
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spacenick/d8b6150fa22f3a40939f to your computer and use it in GitHub Desktop.
Save spacenick/d8b6150fa22f3a40939f to your computer and use it in GitHub Desktop.
Save batches of objects

You need the async library for this function

var saveBatch = function(source, callback, limit) {
	limit = limit || 20;
    var nbSlices = Math.ceil(source.length / limit), i = 0;
    
    async.whilst(function() {
        return i < nbSlices;
    },
    function(cb) {
        var chunk = source.slice(i * limit, (i+1) * limit);
        Parse.Object.saveAll(chunk)
        .then(function() {
            i++;
            cb();
        },
        function(err) {
            cb(err);
        });
    },
    callback);

} 

And you'd use it like

var myArrayOfObjects = [......]
saveBatch(myArrayOfObjects, function(err) {
    if (err) {
     console.log(err)
     }
     else {
        console.log(myArrayOfObjects.length + " objects saved!")
     }  
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment