#Is there a better way to work with promises and callback?
var result = doSomething();
var param = (result[x]) ? 'foo' : 'bar';
var otherResult = doSomethingElse(param);
var saveResult = saveSomething(otherResult);
return json(saveResult);
doSomething( function(err, result){
var param = (result[x]) ? 'foo' : 'bar';
doSomethingElse(param, function(err, otherResult){
saveSomething(otherResult, function (err, saveResult){
return json(saveResult);
});
});
});
###asynchronous programming promises pseudo example:
doSomething().then(function(result){
var param = (result[x]) ? 'foo' : 'bar';
doSomethingElse(param).then(function(otherResult){
saveSomething(otherResult).then(function(saveResult){
return json(saveResult);
}, function(error){
});
}, function(error){
});
}, function(error){
});
Your second example is bad. You can return a promise within a promise.
So it definitely avoids callback hell. There are certian cases however that callback hell might sneak into promises, usually when asynchronously waiting for multiple functions and or other race conditions. However, All callbacks can end. There are other ways also to keep things pretty.
https://github.com/caolan/async
https://github.com/tj/co
amoung them
It can be awefuly ugly, but thats a sacrifice made for lack of threading or inherent async handling like Go