Instantly share code, notes, and snippets.

Embed
What would you like to do?
use promises to batch delete things. Resolve when all complete
save: ->
# avoid making a request before one comes back
return if @prop('busy')
@prop('busy', true)
# we want to delete first so that when we call save we get updated response without the deleted models
@delete().then =>
@save()
.then (models) =>
# # add the response of models to the collection
@reset(models) if models.length
@finishSave()
Promise.resolve()
.catch (xhr) =>
@remove(@getUnsavedModels())
for error in XhrErrors.parseTransportErrors(xhr)
if error.field
error = error.message
GlobalMessageMediator.send
resource : @parentModel.resource
content : error
severity : 'error'
@finishSave()
finishSave: ->
@prop('busy', false)
@prop('inEditMode', false)
delete: ->
return Promise.resolve() unless @prop('modelsToDelete').length
@gatherPromises().then (promiseBatches) ->
# flattens aray of promise arrays
promises = [].concat.apply([], promiseBatches)
Promise.all promises
delayedBatchDelete: (resolvers) ->
setTimeout =>
@deleteBatch(resolvers)
if @prop('modelsToDelete').length
@delayedBatchDelete(resolvers)
, @TAG_RATE_LIMIT_PERIOD
deleteBatch: (resolvers) ->
deleteBatch = @prop('modelsToDelete').splice(0, @TAG_DELETE_RATE_LIMIT)
resolve = resolvers[0]
resolvers.shift()
resolve (model.destroy(silent:true) for model in deleteBatch)
gatherPromises: ->
resolvers = []
promises = []
batchCount = Math.ceil(@prop('modelsToDelete').length/@TAG_DELETE_RATE_LIMIT)
for i in [1..batchCount]
promise = new Promise (resolve) ->
resolvers.push resolve
promises.push promise
# delete first 10 and delay the remainin batches
@deleteBatch(resolvers)
@delayedBatchDelete(resolvers) if batchCount > 1
Promise.all promises
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment