Assuming you have to chain function that return promises, where each function needs values returned by some (not necessarily the last) other promise.
Does this pattern have a name, and is it feasible cleanly with promises ?
E.g :
return getA().then(function (a) {
getB(a).then(function (b) {
getC(a, b).then (function (c) {
return {
a : a,
b : b,
c : c
}
});
});
});
You can't "naively" flatten this :
getA().then(function (a) {
return getB(a);
}).then(function (b) {
// Obviously won't work since a is not there any more
return getC(a, b);
}).then(function (c) {
// Same game, you can't access a or b
});
The only alternative I can see is that getA, getB and getC actually return a Promise resolved with an object containing a, then b, then c. (So each function would build it's part of the final result.)
getA().then (function (result) {
return getB(result.a);
}).then(function (result) {
return getC(result.a, result.b);
}).then(function (result) {
// Last function is useless, just here to illustrate.
return result;
});
Is there a way to flatten the code in my first example?