From 3f0a3f526b57150f8f5541588fa4915fdd45fe3b Mon Sep 17 00:00:00 2001 From: Taner Topal Date: Fri, 13 Jul 2012 15:53:22 +0200 Subject: [PATCH] modified destroyAll --- lib/abstract-class.js | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/lib/abstract-class.js b/lib/abstract-class.js index ed256d38..8c6fdde6 100644 --- a/lib/abstract-class.js +++ b/lib/abstract-class.js @@ -81,7 +81,7 @@ function AbstractClass(data) { }.bind(this)); function getDefault(attr) { - var def = properties[attr]['default'] + var def = properties[attr]['default']; if (isdef(def)) { if (typeof def === 'function') { return def(); @@ -94,7 +94,7 @@ function AbstractClass(data) { } this.trigger("initialize"); -}; +} AbstractClass.setter = {}; AbstractClass.getter = {}; @@ -267,7 +267,7 @@ AbstractClass.count = function (where, cb) { AbstractClass.toString = function () { return '[Model ' + this.modelName + ']'; -} +}; /** * Save instance. When instance haven't id, create method called instead. @@ -368,7 +368,7 @@ AbstractClass.prototype.destroy = function (cb) { this._adapter().destroy(this.constructor.modelName, this.id, function (err) { removeFromCache(this.constructor, this.id); destroyed(function () { - cb && cb(err); + if(cb) cb(err); }); }.bind(this)); }); @@ -510,7 +510,7 @@ AbstractClass.belongsTo = function (anotherClass, params) { var fk = params.foreignKey; this.schema.defineForeignKey(this.modelName, fk); - this.prototype['__finders__'] = this.prototype['__finders__'] || {} + this.prototype['__finders__'] = this.prototype['__finders__'] || {}; this.prototype['__finders__'][methodName] = function (id, cb) { anotherClass.find(id, function (err,inst) { @@ -521,7 +521,7 @@ AbstractClass.belongsTo = function (anotherClass, params) { cb(new Error('Permission denied')); } }.bind(this)); - } + }; this.prototype[methodName] = function (p) { if (p instanceof AbstractClass) { // acts as setter @@ -613,15 +613,27 @@ function defineScope(cls, targetClass, name, params, methods) { this.build(data).save(cb); } + /* + Callback + - The callback will be called after all elements are destroyed + - For every destroy call which results in an error + - If fetching the Elements on which destroyAll is called results in an error + */ function destroyAll(cb) { targetClass.all(this._scope, function (err, data) { if (err) { cb(err); } else { - data.forEach(function (el) { - el.destroy(); - }); - cb(); + (function loopOfDestruction (data) { + if(data.length > 0) { + data.shift().destroy(function(err) { + if(err && cb) cb(err); + loopOfDestruction(data); + }); + } else { + if(cb) cb(); + } + }(data)); } }); }