I got a function requestJSON that queries an external API and returns a (bluebird) promise.
Problem: b gets resolved before c is added to the list so the promise.all runs while only a and b are resolved.
Code:
let promises = [];
// push promise a
promises.push(requestJSON(..));
// push promise b
promises.push(requestJSON(..).then((response) {
// push promise c
promises.push(requestJSON({foo: response.bar});
});
promises.all((data) => {
console.log(data.length) // --> 2
});
Question: I couldn't come up with a really satisfying solution for this problem. Is there a node-way / best-practice?
Possible solutions
(I) Wrap b in another promise and resolve it inside c.then.
Problem: One extra promise that doesn't really do much except cluttering the code.
let promises = [];
// push promise a
promises.push(requestJSON(..));
// push helper promise
promises.push(new Promise((resolve, reject) => {
// push promise b
promises.push(requestJSON(..).then((response) {
// push promise c
promises.push(requestJSON({foo: response.bar});
// resolve helper promise
resolve();
}).catch(..);
}));
promises.all((data) => {
console.log(data.length) // --> 4
});
(II) Put everything inside b.then.
Problem: There's no semantic reason to place a and promise.all inside b + that solution reminds me of the pre-promise callback madness.
let promises = [];
// push promise b
promises.push(requestJSON(..).then((response) {
// push promise a
promises.push(requestJSON(..));
// push promise c
promises.push(requestJSON({foo: response.bar});
promises.all((data) => {
console.log(data.length) // --> 3
});
});