There are two things that, IMHO, make code cleaner when using Promises Idioma:
- use an unique object argument (and its attributes as you would use argument legacy)
- return resolve with the object given as argument augmented by attribute of the action executed by the function
i.e., say I want to ask db for data about a person, I define the method (function) that got an object {person: {personstruct}} and return the augmented object {person:{personstruct}, contactdata: {contactdatastruct}}
function addContactData(o){
return new Promise(function(resolve,reject) {
//check existense of attributes, reject with reason
mysql.query({sql:"select * from cdata where pid=?",values:[o.person.pid]},function(err,rows) {
if(err) {
o.err = err.toString();
reject(o);
} else {
if(rows.length>0) {
o.contactdata = rows[0];
} else {
o.contactdata = null;
}
resolve(o);
}
});
});
}
That could look not very optimized but it is a practice that make things look cleaner and consistent. Pros:
- testing is simply composable, just pass some good object and test if it augments: there is an idioma testing
- you have no surprise
- you have not to deal with “how do I access previous promise result in a .then() chain” problem, where Bergi show some drawback with this solution, that really are worth paying for the cleaness
Also object is passed by reference, and test on required attributes is a matter of enstabilish a protocol, like attrlist with type required.
Note: image source http://www.geograph.org.uk/photo/1804846 chain at the launch of SS Great Eastern (sailing ship), Isle of Dogs, England