function doSomething(pushEight);
function pushEight(res){
res.push(88);
pushNine(res);
}
function pushNine(res){
res.push(99);
showResults(res);
}
function showResults(res){
console.log(res.join(', '));
}
In addition to the anonymous functions I can't reuse elsewhere?
Serious question, just asking..
- Your functions are coupled and cooperate on shared mutable state (you can't pushNine and then pushTen). In large projects coupling like that starts to hurt a lot, so you need more isolated functions and store intermediate state somewhere - and closures are convenient for that, but don't nest too gracefully.
- You don't have error handling. Promises don't make it bulletproof, but at least allow handling most errors in one place (so you don't need `if (err) return callback(err)` in every callback).
But IMHO the `.then()` syntax is just a temporary solution. Promises become really awesomene with ES6 generators or ES7 async/await:
async function doSomething(){
showResults([await getEight(), await getNine()])
}
These snippets are not even remotely equal. Leave the former untouched and modify the latter to this and you have somewhat equal semantics:
function doSomething(null, pushEight);
function pushEight(err, res) {
if (err) return error(err);
try {
res.push(88);
pushNine(res);
}
catch (e) {
error(e);
}
}
function pushNine(err, res){
if (err) return error(err);
try {
res.push(99);
showResults(res);
}
catch (e) {
error(e);
}
}
function showResults(err, res) {
if (err) return error(err);
try {
console.log(res.join(', '));
}
catch (e) {
error(e);
}
}
function error(err) {
console.error(err.stack);
}
If you attach a `.catch(function(err){...})` at the end of the promise chain, then replace that function's body with the body of the error callback that just logs the trace.
* Callbacks passed to cb-based libraries may be called twice - promises are only resolved once, either fulfilled or rejected.
* Callback-based libraries may blow up if the callback throws - promise libraries shield the callback stack from "blowing up" (but do require slightly less careless management of resources at the call-stack site)
* Callbacks passed to cb-based libraries may be called before the current even tick completes, potentially creating the zalgo problem - callbacks attached to promises are always called after the currently executed function finishes.
You're making an argument about callback aggregation. That is just one of the features that promises enable. The seminal article on the topic is Domenic Denicola's "You're Missing the Point of Promises." http://domenic.me/2012/10/14/youre-missing-the-point-of-prom...
as someone else has already mentioned, you're not using the second (error-handling) argument to .then(). you might also check out the aosa on twisted (http://www.aosabook.org/en/twisted.html). twisted's Deferreds seem fairly similar to javascript promises as far as i can gather.