簡體   English   中英

在承諾內返回承諾的價值

[英]Returning the value of promise inside a promise

我有一些需要在返回函數之前完成的承諾。 我有一個承諾可以找回個人資料。 如果配置文件是artist類型,我想使用該配置文件上的itunesId屬性獲取一些json數據,那么我想從promise中返回並訪問配置文件值和json數據。 如果配置文件是fan類型,則在檢索到配置文件后,它應該只返回該配置文件。

我正在嘗試類似的方法,但我知道這是錯誤的,只是不知道如何使其工作。 目前,當我打印music它說是不確定的。 我知道getiTunesMusic函數確實可以正確返回對象數組。

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
})

據我所知, getiTunesMusic(id)返回一個Promise。 因此,這種情況下的結果是這樣的數組: [profile, Promise]

相反,您需要的是這樣鏈接您的內在承諾:

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

從傳遞給next回調的回調中返回Promise會導致Promise,該Promise僅在兩個Promise都解決時才解決,並且其結果是內部Promise的結果。 在這種情況下,您想要的是[profile, music]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM