Resolving an array of promises from a parent promise

This is my first shot in nested promises. I use the bluebird library, but I think the idea is the same for all promise libraries.

At a high level, this is what I am trying to do:

myService.getSomeData(url) .then((data) => { myOtherService.getMoreData(data.uniqueId) .then((thisDataIsAnArray) => { //loop over the data above and do something }); }); 

getMoreData() should make X-service calls and store the results in an array of X elements. Here I start to be mistaken, because I'm not sure how to create this method and what I should return from it. I took a few hits at bluebird Promise.all and Promise.map , but I was floundering and thought I would ask for offers.

+2
javascript promise bluebird
May 6 '16 at 9:12
source share
2 answers

Return all promises!

Promises are just return values ​​to which you attach callbacks, instead of passing callbacks to functions. If you do not return all of them, then there is no way to intercept calls or catch all their errors.

Also, come back with all .then the moment you have another promise. This smooths the situation.

+3
May 7 '16 at 4:21
source share

The promise of iteration completely distorted my brain the first time I tried it. I think that the Bluebird documentation does a rather poor job than the usual use cases, but I will not continue it because (a) I love Bluebird, and (b) I do not have time to update the documents.

It seems to me that 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 used .map , you can also use .reduce or .each . Please note that .each does not change the return value from the promise to which it is attached, so the β€œuse only for side effects” comment in Bluebird docs.

The difference between instance and static methods, of course, is that with statics you have to provide an array, for example. Promise.map(array, (item) => {}) .

Also, as @jib said, always return a value inside your callbacks. It will save you from pain.

+2
May 7 '16 at 11:36 a.m.
source share



All Articles