resolving an array of promises from within a parent promise
Promises are just return values you attach callbacks to, instead of passing callbacks into functions. Unless you return all of them, there's no way for the callbacks to chain, or catch all their errors.
Also, return from all the .then
's the instant you have another promise. This flattens things.
Promise iteration totally warped my brain the first time I tried it as well. I think Bluebird's documentation does a fairly poor job distinguishing the common use cases but I'll not go on about it because (a) I love Bluebird, and (b) I don't have the time to update the docs.
I feel like Promise.map
is the right thing for your scenario.
myService.getSomeData(url)
.then((data) =>
{
return myOtherService.getMoreData(data.uniqueId)
})
.map((item) =>
{
return doSomethingWithData(item);
})
.then((results) =>
{
// do something with the result array.
});
Depending on what you want to do with the results, where I've used .map
you can also use .reduce
, or .each
. Note that .each
does not modify the return value from the promise to which it's chained, hence the "use only for side-effects" comment in the Bluebird docs.
The difference between the instance and static methods is, of course, that with static you must supply the array, e.g. Promise.map(array, (item) => {})
.
Also, as @jib said - always return a value inside your callbacks. This will save you much pain down the line.