Skip to content

Instantly share code, notes, and snippets.

@evandrix
Created December 3, 2012 04:55
Show Gist options
  • Select an option

  • Save evandrix/4192793 to your computer and use it in GitHub Desktop.

Select an option

Save evandrix/4192793 to your computer and use it in GitHub Desktop.
jQuery Nested Callbacks using Deferred Object
app.saveRows = function(obj) {
var d = new $.Deferred(),
count = obj.rows.length;
$.each(obj.rows,function(i, row) {
row.parentId = obj.id;
$.post(otherURL,row,function(data2) {
count--;
$.when(app.saveImgs(row))
.then(function() {
if (count == 0) {
d.resolve();
}
});
});
});
return d.promise();
};
app.saveImgs = function(row) {
var d = new $.Deferred(),
count = row.imgs.length;
$.each(row.imgs,function() {
$.post(uploadURL,this,function() {
count--;
if (count == 0) {
d.resolve();
}
});
}
return d.promise();
};
app.saveObj = function(obj) {
$.when($.post(someURL,obj,function(data) { obj.id = data.id; }))
.then(app.saveRows(obj))
.then(app.renderObj(obj));
};
app.saveObj = function(obj) {
obj.rowsToSave = obj.rows.length;
$.post(someURL,obj,function(data) {
$.each(obj.rows,function() {
var row = this;
row.parentId = data.id;
obj.imgsToSave += row.imgs.length;
$.post(otherURL,row,function(data2) {
$.each(row.imgs,function() {
this.rowId = data2.id;
$.post(uploadURL,this,function() {
obj.imgsToSave--;
if (obj.imgsToSave == 0) {
obj.rowsToSave--;
if (obj.rowsToSave == 0) {
app.renderObj(obj);
}
}
});
});
if (row.imgs.length == 0) {
obj.rowsToSave--;
if (obj.rowsToSave == 0) {
app.renderObj(obj);
}
}
});
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment