Skip to content

Instantly share code, notes, and snippets.

@slmyers
Last active November 30, 2015 23:03
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 slmyers/c44c104a537d825da6d7 to your computer and use it in GitHub Desktop.
Save slmyers/c44c104a537d825da6d7 to your computer and use it in GitHub Desktop.
collection of callback hell and fixes from various websites
// http://thecodebarbarian.com/2015/03/20/callback-hell-is-a-myth
// some things changed because I have to copy from image
describe('.totalValue', function()
it('should calculate the total value of items in a space', function(done){
var table = new Item('table', 'dining room', '1', '3000');
var chair = new Item('chair', 'living room', '3', '300');
var couch = new Item('couch', 'living room', '2', '1100');
var chair2 = new Item('chair', 'dining room', '4', '500');
var bed = new Item('bed', 'bed room', '1','2000');
table.save(function(){
chair.save(function(){
couch.save(function(){
chair2.save(function(){
bed.save(function(){
Item.totalValue({room: 'dining room'}, function(totalValue){
expect(totalValue).to.equal(5000);
done();
})
});
});
});
});
});
});
)};
// fix #1
function create(items, callback) {
var numItems = items.length;
var done = false;
for (var i = 0; i < items.length; ++i) {
items[i].save(function(error) {
if (done) {
return;
}
if (error) {
done = true;
return callback(error);
}
--numItems || callback();
});
}
}
// fix 2
function create(items, callback, index) {
index = index || 0;
if (index >= items.length) {
callback();
}
items[i].save(function(error) {
if (error) {
return callback(error);
}
create(items, callback, index + 1);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment