There are methods such as Q.reduce
and Q.all
that help flattening a promise chain on the specific case of heterogeneous collections of promises. Mind, though, the generic case:
const F = (x) => x;
const a = F(1);
const b = F(2);
const c = F(a + b);
const d = F(a + c);
const e = F(b + c);
console.log(e);
That is, a sequence of assignments on which each term depends on arbitrary previously defined terms. Suppose that F
is an asynchronous call:
const F = (x) => Q.delay(1000).return(x);
I can think in no way to express that pattern without generating an indentation pyramid:
F(100).then(a =>
F(200).then(b =>
F(a+b).then(c =>
F(a+c).then(d =>
F(b+c).then(e =>
F(d+e).then(f =>
console.log(f)
)
)
)
)
)
);
Note that using returned values wouldn't work:
F(100).then(a => F(200))
.then(b => F(a+b))
.then(c => F(a+c))
.then(d => F(b+c))
.then(e => F(d+e))
.then(f => console.log(f));
Since, for example, a
wouldn't be in scope on the second line. What is the proper way to deal with this situation?