Tometoyou
Tometoyou

Reputation: 8406

Returning the value of promise inside a promise

I have a few promises that need to complete before the function is returned. I have one promise that retrieves a profile. If the profile is of type artist I want to the get some json data using the itunesId property on that profile, then I want to return from the promise and access both the profile value and the json data. If the profile is of type fan then after the profile has been retrieved, it should just return the profile.

I'm trying something like this, but I know it is wrong, I just don't know how to make it work. Currently when I print out music it says it's undefined. I know the getiTunesMusic function does correctly return an array of objects.

var promises = []
var profilePromise = userRef.get().then(doc => {
  if (doc.exists) {
    var profile = doc.data()
    profile.id = doc.id

    if (type === UserType.artist) {
      if (profile.hasOwnProperty("itunesId")) {
        return [profile, getiTunesMusic(profile.itunesId)]
      } else {
        return profile
      }
    } else {
      return profile
    }
  } else {
    throw new Error("Profile doesn't exist")
  }
})


promises.push(profilePromise)

// Later on
Promise.all(promises)
.then(objects => {
  var profile = objects[0]
  var music = objects[1]
  console.log(music) // Undefined
})

Upvotes: 0

Views: 73

Answers (1)

Oly
Oly

Reputation: 2479

As far as I can tell, getiTunesMusic(id) returns a Promise. So the result in this case is an array like this: [profile, Promise].

What you need instead is to chain your inner promise like this:

return getiTunesMusic(profile.itunesId).then(music => [profile, music]);

Returning a Promise from the callback passed to next results in a Promise which resolves only when both promises resolve, and whose result is the result of the inner Promise. In this case, [profile, music] which is what you intend.

Upvotes: 1

Related Questions