by dpweb · 12y ago · 0 comments
doSomething().then(function(result) {
var results = [result];
results.push(88);
return results;
}).then(function(results) {
results.push(99);
return results;
}).then(function(results) {
console.log(results.join(', ');
});
More attractive/readable and superior to this? 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()])
} 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.
https://www.dartlang.org/slides/2013/06/dart-streams-are-the...
It's Dart instead of JS, but the idea is pretty much the same.