Promise a promise to simple promises?

I have been playing around with promises and can usually figure out how to handle them correctly, but in this situation, I cannot figure out how to remove one level of wrapping.

Here is the code:

let promise2 = promise1.then((nodes) => {
  return Promise.all(nodes.map(n => {

    // findConnections returns a promise
    return this.findConnections(n.get("spotifyData")); 
  }));
});

      

Now I would expect prom2 to carry over the array, but it doesn't, this completes the promise that ends the array. If I want to access the array, I have to do this:

promise2.then(level1 => level1.then(level2 => console.log(level2)));

      

level1 is the promise itself.

Of course I could handle this, but I find the code very ugly and I would like to simplify it so that you can:

promise2.then(level1 => console.log(level1))

      

and directly get the array there.

Any ideas?

Thank!

EDIT:

FindConnections () method:

findConnections: function (node) {
  return Ember.$.get("https://api.spotify.com/v1/artists/" + node.id + "/related-artists").then((data) => {
     return data.artists;
  });
}

      

+3


source to share


1 answer


level1

- the promise itself.

No no. Ember does indeed use RSVP , which is Promises / A + compatible , which means that then

callbacks are never called with a promise (or then). They always get equal value.

Promises / A + indicates that there are no nested promises returned from then

. They always unfold recursively. You can just do



promise2.then(connections => console.log(connections));

      

If that doesn't really work, it assumes that promise1

it is not a real (or at least standard) convention and you must follow through first promise1 = Promise.resolve(promise1)

.

+1


source







All Articles