developping a restful app with nodejs, expressjs and sequelizejs, I found my code doing a lot of callbacks.
In particular when I'm dealing with association and creating object in db like so:
// db is my database object
// here are my db entities : header, line and thing
// header has many line
// line belongs to header
// line has one thing
// thing has many line
db.line.create().success(function(line){
db.header.find({where:{id : header_id}}).success(function(header){
header.addLine(line).success(function(){
db.thing.find({where:{id : thing_id}}).success(function(thing){
line.setThing(thing).success(function(){
// OK
});
});
});
});
});
I wanted to use return
statement inside error callback but I wouldn't be able to get the created data.
Do you think there is another way to do such operations without all the callbacks?
With previous example this is what promises would look likes in my example of creating and associating :
// db is my database object
// here are my db entities : header, line and thing
// header has many line
// line belongs to header
// line has one thing
// thing has many line
db.line.create().success(function(line){
db.header.find({where:{id : header_id}
}).then(function(header){
header.addLine(line);
}).then(function(){
return db.thing.find({where:{id : thing_id}
}).then(function(thing){
line.setThing(thing);
}).then(function(){
// OK
}).catch(function(err){
// handle errors of association
});
.error(function(err){
// handle errors of creation
});