I have an async javascript app for browser and I want to use promises. Every async call has same pattern which can be transformed in promise. My problem is that I have data dependencies in callback chain. Some simplified code:
getAlpha(function(err, alpha){
if(err) {handleError(err); return;}
getBeta(function(err, beta){
if(err) {handleError(err); return;}
getOmega(function(err, omega){
if(err) {handleError(err); return;}
getEpsilon(beta, function(err, epsilon){ // depends on beta
if(err) {handleError(err); return;}
getDelta(beta, function(err, delta){ // depends on beta
if(err) {handleError(err); return;}
console.log(alpha + beta + omega + epsilon + delta);
});
});
});
});
});
I see two problems with promises here:
There are data dependencies between callback calls. getEpsilon and getDelta depends on beta value.
I need all collected data in the last callback from the very first call and other.
I look here http://stuk.github.io/promise-me/ for some examples. "Captured variables" example solve both problems but it makes the same callback ladder which we see without promises.
Other way is making data object to store all promise returns. It looks like this:
var res = {};
getAlpha().then(function(alpha){
res.alpha = alpha;
return getBeta();
}).then(function(beta){
res.beta = beta;
return getOmega();
}).then(function(omega){
res.omega = omega;
return getEpsilon(res.beta);
}).then(function(epsilon){
res.epsilon = epsilon;
return getDelta(res.beta);
}).then(function(delta){
res.delta = delta;
console.log([res.alpha, res.beta, res.omega, res.epsilon, res.delta].join(' '));
}).catch(function(err){
handleError(err);
});
I wonder if it is possible to solve this problem without nested calls and data container.
UPD 1. I'm very sorry but my first promise solution doesn't work at all so I make correct version.
UPD 2. In original code each get-LETTER call is a GET http request so these calls can work in parallel.
UPD 3. Thanks to robertklep and Jeff Bowman. I tried both answers. I like robertklep version because it is very short. After Jeff Bowman version I understand many potential issues in my asynchronous execution.
UPD 4. I mixed my initial promise solution with robertklep version to add some sugar.
var R = require('ramda');
// getAlpha returns alpha, etc.
var promiseObj = function(obj, res){
var promises = R.transpose(R.toPairs(obj));
return new Promise(function(resolve, reject){
Promise.all(promises[1]).then(function(results){
res = res || {};
resolve(R.merge(res, R.zipObj(promises[0], results)));
});
});
};
promiseObj({
'alpha' : getAlpha(),
'beta' : getBeta()
}).then(function(res){ // res: { alpha: 'alpha', beta: 'beta' }
return promiseObj({
'epsilon' : getEpsilon(res.beta),
}, res);
}).then(function(res){
console.log(res); // res: { alpha: 'alpha', beta: 'beta', epsilon: 'beta_epsilon' }
});
P.S. How do I access previous promise results in a .then() chain? gives answer to my question too but in more generic way.